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();
    }
}
  • 第二步:创建HelloController类,当访问eureka-client的/hello服务的时候,发送一个http请求 http://eureka-client2/hello, restTemplate会将域名eureka-client2解析成具体实例的ip地址,最后发送的请求url为 http://localhost:7772/hello .
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;
    }
}
 
  • 第四步:调用http://localhost:7771/hello?name=Robbon
4.springcloud_eureka服务发现ribbon+resTemplate(Finchley.SR2)_第1张图片
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 restTemplates = Collections.emptyList();
    
    // 通过该方法为RestTemplate进行配置,配置类型为RestTemplateCustomizer
    @Bean
    public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(
            final ObjectProvider> 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 list = new ArrayList<>(
                        restTemplate.getInterceptors());
                list.add(loadBalancerInterceptor);
                restTemplate.setInterceptors(list);
            };
        }
    }
...

可以发现LoadBalancerAutoConfiguration做了以下事情

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

        // 在这里将我们注册的RestTemplate放入restTemplates里面
      @LoadBalanced
      @Autowired(required = false)
      private List 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 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> 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

你可能感兴趣的:(4.springcloud_eureka服务发现ribbon+resTemplate(Finchley.SR2))