springcloud+nacos服务之间调用的几种方式

springcloud+nacos服务之间调用的几种方式,第1张

springcloud+nacos服务之间调用的几种方式 1. springcloud内置的负载均衡客户端获取服务ip和端口
    @Autowired
    private LoadBalancerClient loadBalancerClient;

	//通过服务名获取到服务的ip和端口,随后通过restTemplate或者okhttp等请求
    public void test() {
    	ServiceInstance choose = loadBalancerClient.choose("jzhy-order");
    	String url = "http://" + choose.getServiceId() + ":" + choose.getPort();
    	System.out.println(url);
    	System.out.println(choose.getHost());
    	System.out.println(choose.getUri());
    	
	}
2. nacos通过服务名称获取服务ip和端口
	//获取nacos管理,由于nacos的bug,只能注入一下两个类来实现
	@Autowired
	private NacosServiceManager nacosServiceManager;
	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;

	public void test(){
		String url = "";
		try {
			NamingService namingService = nacosServiceManager
					.getNamingService(nacosDiscoveryProperties.getNacosProperties());
			Instance instance = namingService.selectOneHealthyInstance(ServiceNameConstants.JZHY_FILE_SERVICE);
			url = StrUtil.format("http://{}:{}/upload", instance.getIp(), instance.getPort());

		} catch (NacosException e) {
			e.printStackTrace();
			throw new CustomException("从注册中心获取文件服务异常", e);
		}
	}

	//同样根据服务名称获取到服务ip和端口,直接发起http请求
3. FeignClient 远程调用
// 先写个客户端

@FeignClient(contextId = "remoteOrderService", value = ServiceNameConstants.JZHY_ORDER, fallbackFactory = RemoteOrderFallbackFactory.class)
public interface RemoteOrderService
{
    @GetMapping("/test")
    public String getUserInfo();
}

// 再来个Factory
@Component
public class RemoteOrderFallbackFactory implements FallbackFactory
{
    private static final Logger log = LoggerFactory.getLogger(RemoteOrderFallbackFactory.class);

    @Override
    public RemoteOrderService create(Throwable throwable)
    {
        log.error("order服务调用失败:{}", throwable.getMessage());
        return new RemoteOrderService()
        {

			@Override
			public String getUserInfo() {
				return "获取失败:" + throwable.getMessage();
			}};
    }
}

// 继续在 meta-INF/spring.factories 文件中声明Factory

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5609354.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存