ribbon 实现负载均衡

如官方文档所说:To include Ribbon in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-ribbon

注解 @LoadBalance 实现客户端的负载均衡

@Bean
@LoadBalanced       //如果这里不加这个注解,使用serviceID调用微服务时,将会出现 UnknownHostException 异常
public RestTemplate restTemplate(){
    return new RestTemplate();
}

比如:在微服务 consumer-movie 调用微服务 provider-user ,可以像下面这样调用, host:port用spring.application.name代替

@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id){
   System.out.println("movie/id");
   return restTemplate.getForObject("http://provider-user/simple/"+id, User.class);
}

customizing ribbon:

新建一个configuration类,添加注解@Configuration,你可以重写以下这些beans实现你想要的负载均衡的rule:
(BeanType beanName: ClassName):

IClientConfig ribbonClientConfig: DefaultClientConfigImpl

IRule ribbonRule: ZoneAvoidanceRule

IPing ribbonPing: NoOpPing

ServerList<Server> ribbonServerList: ConfigurationBasedServerList

ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter

ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

例如:

//默认规则为轮询, 这个为随机规则
//该类必须放置在扫描不到的包下, 或者添加排除(见下文看我如何添加排除!!!), 虽然他必须有注解(spring boot默认扫描application所在的包及其子包)
@Configuration
public class FooConfiguration {
    @Bean
    public IRule ribbonPing(IClientConfig config) {
        return new RandomRule();
    }
}

在需要配置ribbon的类添加注解:@RibbonClient(name = "provider-user",configuration =FooConfiguration.class )
其中:name为请求的服务的serviceID,也就是spring.application.name配置的值
configuration为上文中新建的类,也就是配置ribbon的rule的类。详细请看下文,ribbon源代码:

/**
 * A custom <code>@Configuration</code> for the ribbon client. Can contain override
 * <code>@Bean</code> definition for the pieces that make up the client, for instance
 * {@link ILoadBalancer}, {@link ServerListFilter}, {@link IRule}.
 *
 * @see RibbonClientConfiguration for the defaults
 */
Class<?>[] configuration() default {};

添加排除,也就是说让 @componentScan 扫描不到这个类:

step1.自定义一个注解
package com.cloud.microservice.consumermovie.annotation;
/**
 * 自定义注解, 排除不想被扫描到的内容
 * @Author: yuju
 * @Date: 2018/5/10 - 10:55
 */
public @interface ExcudeAnnotation {
}
step2.在需要添加排除的类添加注解 @ExcudeAnnotation
/**
 * @Author: yuju
 * @Date: 2018/5/8 - 9:41
 */
@Configuration
@ExcudeAnnotation   //就是上文自定义的注解啦
public class TestConfiguration {
    @Autowired
    IClientConfig config;
    @Bean
    @ConditionalOnMissingBean
    public IRule ribbonRule(IClientConfig config) {
        return new RandomRule();
    }
}
step3.在使用该策略的地方加上注解 @ComponentScan(...)
package com.cloud.microservice.consumermovie;

import com.cloud.microservice.config.TestConfiguration;
import com.cloud.microservice.consumermovie.annotation.ExcudeAnnotation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "provider-user",configuration =TestConfiguration.class )
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = ExcudeAnnotation.class)})
public class ConsumerMovieRibbonApplication {
    @Bean
    @LoadBalanced //负载均衡
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(ConsumerMovieRibbonApplication.class, args);
    }
}
step4.现在你就可以把它放在主类的包下面了

测试

loadbalancerClient

推荐阅读更多精彩内容