4.springcloud_eureka服务发现ribbon+r

2019-02-24  本文已影响0人  机智的jack

这是一个从零开始的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.

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);
    }
}
 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

总结一下以上请求流程


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

@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做了以下事情

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


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

上一篇 下一篇

猜你喜欢

热点阅读