服务消费方Feign & RestTemplate

超、凢脫俗 2022-06-02 05:09 295阅读 0赞

在Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign,鉴于feign注解化更方便使用,先讲解feign.

demo中使用的注册中心是eureka,如果使用consul,需要修改配置:

  1. #spring:
  2. # profiles:
  3. # active: dev
  4. # application:
  5. # name: service-feign
  6. ###################### consul ###########################
  7. # cloud:
  8. # consul:
  9. # host: 192.168.1.102
  10. # port: 8500
  11. # discovery:
  12. # healthCheckUrl: http://localhost:${server.port}/health
  13. # healthCheckInterval: 15s
  14. # instance-id: service-feign
  15. # enabled: true
  16. # heartbeat:
  17. # enabled: true
  18. /**
  19. * @这个Client由服务提供方提供,如euraka-server-provider里面的client包提供
  20. * @添加@FeignClient注解是为了调用方的在服务注册机器上找到服务提供方
  21. */
  22. @FeignClient(value = "service-provider") //这里的name对应调用服务的spring.applicatoin.name
  23. public interface ServiceFeignClient {
  24. @RequestMapping(value = "/hi")
  25. String hi(@RequestParam("id") String id);
  26. }

使用注解 @EnableFeignClients启动feign

https://github.com/nick8sky/spring-clouds/eureka-consumer-feign

restTemplate:

ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。

注意:ribbon未实现实效转移。

在它的pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web

在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class ClientApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(ClientApplication.class, args);
  6. }
  7. @Bean
  8. @LoadBalanced
  9. RestTemplate restTemplate(){
  10. return new RestTemplate();
  11. }
  12. }

在浏览器上多次访问 http://localhost:8910/hi?name=nick, 浏览器交替显示

  1. @RequestMapping("/hi")
  2. public String hi(@RequestParam String id){
  3. return restTemplate.getForObject("http://service-provider/hi?id="+id, String.class);
  4. }

ribbon架构

20180104161731772

发表评论

表情:
评论列表 (有 0 条评论,295人围观)

还没有评论,来说两句吧...

相关阅读