服务消费方Feign & RestTemplate

服务消费方Feign & RestTemplate

2018年01月04日 15:59:22 llianlianpay 阅读数:3765

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/llianlianpay/article/details/78971910

在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

 
  1. /**

  2. * @这个Client由服务提供方提供,如euraka-server-provider里面的client包提供

  3. * @添加@FeignClient注解是为了调用方的在服务注册机器上找到服务提供方

  4. */

  5. @FeignClient(value = "service-provider") //这里的name对应调用服务的spring.applicatoin.name

  6. public interface ServiceFeignClient {

  7. @RequestMapping(value = "/hi")

  8. String hi(@RequestParam("id") String id);

  9. }

使用注解 @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.  
  8. @Bean

  9. @LoadBalanced

  10. RestTemplate restTemplate(){

  11. return new RestTemplate();

  12. }

  13. }

在浏览器上多次访问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架构

猜你喜欢

转载自blog.csdn.net/f45056231p/article/details/90079487
今日推荐