一、环境
- spring boot 2.x
- spring cloud (Finchley SR2以上版本)
- eureka
二、引入ribbon依赖
<!-- 使用ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<!-- <artifactId>spring-cloud-starter-ribbon</artifactId> 2.x以前版本 -->
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
三、eureka中使用
1. 增加配置
@LoadBalanced
@Bean
public RestTemplate createRestTemplate() {
return new RestTemplate();
}
/**
* 配置ribbon规则
*
* <p>没有配置此属性默认规则为RoundRobinRule轮询
* </p>
* @return
*/
@Bean
public IRule ribbonRule() {
// 随机访问
//return new RandomRule();
// 轮询
return new RoundRobinRule();
}
-
使用ribbion负载: RestTemplate声明中增加@LoadBalanced
-
自定义负载规则:没有声明规则默认的轮询负载模式,声明规则则使用指定的模式
@Bean
public IRule ribbonRule(){}
[负载策略参考](https://blog.csdn.net/rickiyeat/article/details/64918756)
spring cloud官网参考(http://cloud.spring.io/spring-cloud-static/Edgware.SR2/single/spring-cloud.html#spring-cloud-ribbon)
2.使用
@RestController
public class RibbonTestContraller {
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/test1")
public String test1(@RequestParam(required = false, value = "name") String name) {
// PROVIDER注册在eureka上的服务名
String url = "http://PROVIDER/client";
String result = restTemplate.getForObject(url, String.class);
return result;
}
@GetMapping("/test2")
public String test2() {
ServiceInstance serviceInstance = loadBalancerClient.choose("PROVIDER");
String result = "host=" + serviceInstance.getHost() + ",port=" + serviceInstance.getPort() + ",serviceid="
+ serviceInstance.getServiceId();
return result;
}
}
-
test1为restTemplate方式,已经带有ribbon负载了;
-
test2为loadBalancerClient api方式
3.启动应用检查
provider
为你指定的服务名,具体以项目当前设置为准。
第一次访问
Services: [provider] ip :20000
第二次访问
Services: [provider] ip :20001
你注册的服务会按照访问次数轮询出现。
四、单独使用ribbon
1. eureka环境下必须禁用,否则默认的ribbon客户端会覆盖
有eureka的环境禁用设置
ribbon:
eureka:
enabled: false
2. application.yml
stores
stores:
ribbon:
listOfServers: example.com,google.com
3. 代码
loadBalancerClient.choose(“stores”)
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/test3")
public String test3() {
ServiceInstance serviceInstance = loadBalancerClient.choose("stores");
String result = "host=" + serviceInstance.getHost() + ",port=" + serviceInstance.getPort() + ",serviceid="
+ serviceInstance.getServiceId();
return result;
}
4. 检查
启动应用后,访问对应路径即可看到浏览器中交替返回server信息。
五、官方文档
16.2 Customizing the Ribbon Client
You can configure some bits of a Ribbon client using external properties in
<client>.ribbon.*
, which is no different than using the Netflix APIs natively, except that you can use Spring Boot configuration files. The native options can be inspected as static fields inCommonClientConfigKey
(part of ribbon-core).Spring Cloud also lets you take full control of the client by declaring additional configuration (on top of the
RibbonClientConfiguration
) using@RibbonClient
. Example:@Configuration @RibbonClient(name = "foo", configuration = FooConfiguration.class) public class TestConfiguration { }
In this case the client is composed from the components already in
RibbonClientConfiguration
together with any inFooConfiguration
(where the latter generally will override the former).
The FooConfiguration
has to be@Configuration
but take care that it is not in a@ComponentScan
for the main application context, otherwise it will be shared by all the@RibbonClients
. If you use@ComponentScan
(or@SpringBootApplication
) you need to take steps to avoid it being included (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the@ComponentScan
).Spring Cloud Netflix provides the following beans by default for ribbon (
BeanType
beanName:ClassName
):
IClientConfig
ribbonClientConfig:DefaultClientConfigImpl
IRule
ribbonRule:ZoneAvoidanceRule
IPing
ribbonPing:DummyPing
ServerList<Server>
ribbonServerList:ConfigurationBasedServerList
ServerListFilter<Server>
ribbonServerListFilter:ZonePreferenceServerListFilter
ILoadBalancer
ribbonLoadBalancer:ZoneAwareLoadBalancer
ServerListUpdater
ribbonServerListUpdater:PollingServerListUpdater
Creating a bean of one of those type and placing it in a
@RibbonClient
configuration (such asFooConfiguration
above) allows you to override each one of the beans described. Example:@Configuration protected static class FooConfiguration { @Bean public ZonePreferenceServerListFilter serverListFilter() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); filter.setZone("myTestZone"); return filter; } @Bean public IPing ribbonPing() { return new PingUrl(); } }
This replaces the
NoOpPing
withPingUrl
and provides a customserverListFilter
16.3 Customizing default for all Ribbon Clients
A default configuration can be provided for all Ribbon Clients using the
@RibbonClients
annotation and registering a default configuration as shown in the following example:@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class) public class RibbonClientDefaultConfigurationTestsConfig { public static class BazServiceList extends ConfigurationBasedServerList { public BazServiceList(IClientConfig config) { super.initWithNiwsConfig(config); } } } @Configuration class DefaultRibbonConfig { @Bean public IRule ribbonRule() { return new BestAvailableRule(); } @Bean public IPing ribbonPing() { return new PingUrl(); } @Bean public ServerList<Server> ribbonServerList(IClientConfig config) { return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config); } @Bean public ServerListSubsetFilter serverListFilter() { ServerListSubsetFilter filter = new ServerListSubsetFilter(); return filter; } }
16.4 Customizing the Ribbon Client using properties
Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.
This allows you to change behavior at start up time in different environments.
The supported properties are listed below and should be prefixed by
<clientName>.ribbon.
:
NFLoadBalancerClassName
: should implementILoadBalancer
NFLoadBalancerRuleClassName
: should implementIRule
NFLoadBalancerPingClassName
: should implementIPing
NIWSServerListClassName
: should implementServerList
NIWSServerListFilterClassName
should implementServerListFilter
Classes defined in these properties have precedence over beans defined using @RibbonClient(configuration=MyRibbonConfig.class)
and the defaults provided by Spring Cloud Netflix.To set the
IRule
for a service nameusers
you could set the following:application.yml.
users: ribbon: NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
See the Ribbon documentation for implementations provided by Ribbon.