接上回 https://blog.csdn.net/weixin_43119903/article/details/104801613
创建服务的消费者
与创建服务提供者一样,这里就不详细介绍了
在服务的提供者中提供一个接口
@RestController
@RequestMapping("/product")
public class ProductController {
@RequestMapping(value = "/getProduct/{id}",method = RequestMethod.GET)
public String getProduct(@PathVariable Long id){
return "id为:"+id;
}
}
在消费者中调用此接口
可以使用各种工具,通过http请求此接口
只要可以发送http请求,都可以访问此接口,就像前端访问后端一样。如:
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
@RestController
@RequestMapping("/demo")
public class DemoController {
//注入restTemplate
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public String get(@PathVariable Long id){
return restTemplate.getForObject("http://localhost:9001/product/getProduct/"+id,String.class);
}
}
通过注册中心访问此接口
我们可以从注册中心中获取相关服务信息,然后通过这些信息去访问这个接口,获取这些信息可以通过springcloud提供的DiscoveryClient类中的方法去获取
//注入restTemplate
@Autowired
private RestTemplate restTemplate;
/**
* 注入DiscoveryClient
* spring cloud提供的获取原数组的工具类,调用方法获取服务的元数据信息
* */
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public String get(@PathVariable Long id){
//调用discoveryClient方法
List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//里面只有一个instance(因为只有一个product-service)
ServiceInstance instance = instances.get(0);
//通过instance里面的信息,组合成url,访问服务接口
return restTemplate.getForObject("http://"+instance.getHost()+":"+instance.getPort()+"/product/getProduct/"+id,String.class);
}
集成ribbon后可以通过服务名进行获取
restTemplate.getForObject("http://product-service/product/getProduct/"+id,String.class);
怎么集成ribbon,会在往后的章节中提到