1. springcloud内置的负载均衡客户端获取服务ip和端口
@Autowired
private LoadBalancerClient loadBalancerClient;
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和端口
@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);
}
}
3. FeignClient 远程调用
@FeignClient(contextId = "remoteOrderService", value = ServiceNameConstants.JZHY_ORDER, fallbackFactory = RemoteOrderFallbackFactory.class)
public interface RemoteOrderService
{
@GetMapping("/test")
public String getUserInfo();
}
@Component
public class RemoteOrderFallbackFactory implements FallbackFactory<RemoteOrderService>
{
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();
}};
}
}