4.springcloud_eureka服务发现ribbon+resTemplate(Finchley.SR2)

这是一个从零开始的springcloud的系列教程,如果你从中间开始看,可能会看不明白.请进入我的系列教程开始从头开始学习.spring-cloud教程

ribbon+restTemplate

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.

-----摘自官网

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

来看看代码怎么使用Ribbon+RestTemplate.

  • 第一步:在eureka-client工程中创建RibbonConfiguration类,该类负责创建一个RestTemplate对象,@LoadBalanced会给创建RestTemplate增加请求拦截器,该拦截器可以对url进行改写,让其服务名称变为对应的服务实例的ip地址
package com.jack.eureka_client;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RibbonConfiguration {

    // 创建一个装有ribbon请求拦截器的restTemplate
    // @LoadBalanced会给创建RestTemplate增加请求拦截器,该拦截器会将对应的服务名称改成具体实例的域名
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
package com.jack.eureka_client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloController {

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Object hello(@RequestParam(value = "name", required = false) String name) {
        return restTemplate.getForObject("http://eureka-client2/hello?name=" + name, String.class);
    }
}
  • 第三步:在eureka-client2工程里也创建一个HelloController,这样就能收到eureka-client发送的http请求
 package com.jack.eureka_client2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Object hello(@RequestParam(value = "name", required = false) String name) {
        return "Hello " + name;
    }
}
 
image.png

总结一下以上请求流程

  • 客户端发送get请求到eureka-client服务(localhost:7771)上
  • eureka-client服务收到http请求,通过restTemplate对eureka-client2服务发送http请求
  • restTemplate收到http://eureka-client2/hello?name=Robbon请求,将url改写为http://localhost:7772/hello?name=Robbon. localhost:7772是eureka-client2的ip地址
  • eureka-client2收到http请求,返回结果
  • eureka-client收到eureka-client2的结果,返回客户端

很神奇?只需要加入这份神奇的代码,就能完成服务之间的调用了.

@Bean
@LoadBalanced
RestTemplate restTemplate() {
    return new RestTemplate();
}

我们深入一下这部分代码做了什么.

RestTemplate是什么?它是一个spring提供的http请求类,可以十分方便的发送http请求,避免了复杂的代码,假如发送一个http://eureka-client2/hello请求,正常来说发送是失败的,因为域名是找不到的.所以我们需要在发送请求后,对请求进行拦截,将eureka-client2改写成实例实际的ip地址.想要达到这个目的可以为RestTemplate对象设置http拦截器,从而到达改写目的.

@LoadBalanced注解做的就是给RestTemplate设置http请求拦截器.打开LoadBalancerAutoConfiguration文件.

@Configuration
@ConditionalOnClass(RestTemplate.class)
@ConditionalOnBean(LoadBalancerClient.class)
@EnableConfigurationProperties(LoadBalancerRetryProperties.class)
public class LoadBalancerAutoConfiguration {
    
    // 在这里将我们注册的RestTemplate放入restTemplates里面
    @LoadBalanced
    @Autowired(required = false)
    private List<RestTemplate> restTemplates = Collections.emptyList();
    
    // 通过该方法为RestTemplate进行配置,配置类型为RestTemplateCustomizer
    @Bean
    public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(
            final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
        return () -> restTemplateCustomizers.ifAvailable(customizers -> {
            for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) {
                for (RestTemplateCustomizer customizer : customizers) {
                    customizer.customize(restTemplate);
                }
            }
        });
    }
    
    @Configuration
    @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
    static class LoadBalancerInterceptorConfig {
        // ribbon的拦截器,loadBalanceClient由RibbonAutoConfiguration文件创建
        @Bean
        public LoadBalancerInterceptor ribbonInterceptor(
                LoadBalancerClient loadBalancerClient,
                LoadBalancerRequestFactory requestFactory) {
            return new LoadBalancerInterceptor(loadBalancerClient, requestFactory);
        }
        
        // 创建RestTemplateCustomizer,为loadBalancedRestTemplateInitializerDeprecated使用
        @Bean
        @ConditionalOnMissingBean
        public RestTemplateCustomizer restTemplateCustomizer(
                final LoadBalancerInterceptor loadBalancerInterceptor) {
            return restTemplate -> {
                List<ClientHttpRequestInterceptor> list = new ArrayList<>(
                        restTemplate.getInterceptors());
                list.add(loadBalancerInterceptor);
                restTemplate.setInterceptors(list);
            };
        }
    }
...

可以发现LoadBalancerAutoConfiguration做了以下事情

  • 第一步: 将含有@LoadBalanced注解的RestTemplate放入restTemplates数组中

        // 在这里将我们注册的RestTemplate放入restTemplates里面
      @LoadBalanced
      @Autowired(required = false)
      private List<RestTemplate> restTemplates = Collections.emptyList();
    
  • 第二步: 创建LoadBalancerInterceptor拦截器,LoadBalancerClient和LoadBalancerRequestFactory由Ribbon提供,在RibbonAutoConfiguration配置类中创建.

  • // ribbon的拦截器,loadBalanceClient由RibbonAutoConfiguration文件创建
    @Bean
    public LoadBalancerInterceptor ribbonInterceptor(
          LoadBalancerClient loadBalancerClient,
          LoadBalancerRequestFactory requestFactory) {
      return new LoadBalancerInterceptor(loadBalancerClient, requestFactory);
    }
    
  • 第三步:创建RestTemplateCustomizer,该类的作用是给RestTemplate装配LoadBalancerInterceptor

  • @Bean
    @ConditionalOnMissingBean
    public RestTemplateCustomizer restTemplateCustomizer(
      final LoadBalancerInterceptor loadBalancerInterceptor) {
      return restTemplate -> {
              List<ClientHttpRequestInterceptor> list = new ArrayList<(restTemplate.getInterceptors());
            list.add(loadBalancerInterceptor);
            restTemplate.setInterceptors(list);
        };
    }
    
  • 第四步: 对restTemplates中的元素进行装配LoadBalancerInterceptor拦截器,通过customizer.customize(restTemplate)代码来装配,最后达到改写http请求的目的.这里的RestTemplateCustomizer就是第三步创建的

  • // 通过该方法为RestTemplate进行配置,配置类型为RestTemplateCustomizer
      @Bean
      public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(
              final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
          return () -> restTemplateCustomizers.ifAvailable(customizers -> {
                for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) {
                    for (RestTemplateCustomizer customizer : customizers) {
                        customizer.customize(restTemplate);
                    }
                }
            });
      }
    

到此为RestTemplate设置Ribbon提供的LoadBalancerInterceptor拦截器的过程完毕


Cool! Ribbon+RestTemplate的调用方式我们已经深入了解,之后我们来讲解更加人性化调用的Feign

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341