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<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();
}};
}
}
// 继续在 META-INF/spring.factories 文件中声明Factory