1.前提
我们已经成功地将服务提供者:order
或product
注册到了Eureka
服务注册中心,同时我们也可以通过DiscoveryClient
接口的getServices
获取了当前客户端缓存的所有服务清单,那么接下来我们要学习的就是:如何去消费服务提供者的接口
2.使用LoadBalancerClient
从LoadBalancerClient
接口的命名中,我们就知道这是一个负载均衡客户端的抽象定义,下面我们就看看如何使用Spring Cloud
提供的负载均衡器客户端接口来实现服务的消费。
order 服务
1.在启动类将RestTemplate 交给Spring管理
@SpringBootApplication
public class LovingApplication {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(LovingApplication.class, args);
}
}
2.OrderController
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/contact/{goodsId}")
public ServerResponse contact(@PathVariable("goodsId") Long goodsId) {
ServiceInstance serviceInstance = loadBalancerClient.choose("product");
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() +"/product"+ "/search/"+goodsId;
log.info("url: {}", url);
GoodsInfo goodsInfo = restTemplate.getForObject(url, GoodsInfo.class);
return ServerResponse.createBySuccess(goodsInfo);
}
product服务
@GetMapping("/search/{goodsId}")
public GoodsInfo search(@PathVariable("goodsId") Long goodsId){
GoodsInfo goodsInfo = goodsInfoService.findByGoodsId(goodsId);
if(goodsInfo == null){
throw new ProductException(ExceptionCodeEnum.PRODUCT_NOT_EXIT);
}
return goodsInfo;
}
访问地址http://172.16.15.179:2000/order/contact/10003
![](https://img.haomeiwen.com/i8574472/2b26939410818661.png)
3.衍生一种新的RestTemplate调用方式
// 2.使用springCloud提供的 LoadBalancerClient,通过 应用名 获取url
ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
String url = String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort());
json = restTemplate.getForObject(url,String.class);
网友评论