版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013037201/article/details/77118634
从上篇博客我们可以看到,Ribbon默认的负载均衡策略为轮询。如果想自定义改如何配置,小编将在这篇博客带你一步一步完成自定义配置。
在上篇的项目基础上做更改。
一、编写一个注解ExcludeFromComponentScan.java
package com.itmuch.cloud;
public @interface ExcludeFromComponentScan {
}
二 、编写一个TestConfiguration.java,将负载均衡策略变为随机
package com.itmuch.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
@Configuration
@ExcludeFromComponentScan
public class TestConfiguration {
@Autowired
IClientConfig config;
@Bean
public IRule ribbonRule(IClientConfig config){
return new RandomRule();
}
}
public class TestConfiguration {
@Autowired
IClientConfig config;
@Bean
public IRule ribbonRule(IClientConfig config){
return new RandomRule();
}
}
三、修改启动类ConsumerMovieRibbonApplication.java
在类上添加两个注解:
@RibbonClient(name="microservice-provider-user",configuration = TestConfiguration.class)
@ComponentScan(excludeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION,value=ExcludeFromComponentScan.class)})
四、在Controller中添加测试代码:
@Autowired
private LoadBalancerClient LoadBalancerClient;
@GetMapping("/test")
public String test() {
ServiceInstance serviceInstance = this.LoadBalancerClient.choose("microservice-provider-user");
System.out.println("111"+serviceInstance.getHost()+":"+serviceInstance.getPort()+":"+serviceInstance.getServiceId());
ServiceInstance serviceInstance2 = this.LoadBalancerClient.choose("microservice-provider-user2");
System.out.println("222"+serviceInstance2.getHost()+":"+serviceInstance2.getPort()+":"+serviceInstance2.getServiceId());
return "1";
}
五、启动
先启动eureka,再启动四个提供者实例,7900,7901,7902(user2),7903(user2),修改application.yml即可。最后启动消费者。启动成功界面:
六、访问页面:localhost:8010/test,刷新八次。
小结
到这里,自定义配置的展示就完成了。其中的知识点总结一下。
1、扫描包的排除:
@Configuration这个注解是不能@SpringBootApplication的所在扫描到的,否则将自定义的配置将失效。所以需要将TestConfiguration.java排除在包扫描之外,用自定义的注解@ExcludeFromComponentScan,然后在启动类加注解@ComponentScan(excludeFilters{@ComponentScan.Filter(type=FilterType.ANNOTATION,value=ExcludeFromComponentScan.class)})将其排除。
2、自定义负载均衡策略的更换。
@Bean
public IRule ribbonRule(IClientConfig config){
return new RandomRule();
}
这里是关键,还可以换成其它负载均衡策略。
完整的项目源码将在后面分享,敬请期待。。。