Springcloud2020版之后的Ribbon(LoadBalancer)负载算法转换
本篇适用于springcloud2020版本,2020版本之前是有Ribbon的,但是2020版本之后Springcloud把Ribbon移除了,用LoadBalancer替代了。2020版本之前的Ribbon传送门:(23条消息) 更改Ribbon负载均衡配置规则_zuodingquan666的博客-CSDN博客1.新建配置类package com.myrule;import org.sprin
·
本篇适用于springcloud2020版本,2020版本之前是有Ribbon的,但是2020版本之后Springcloud把Ribbon移除了,用LoadBalancer替代了。
2020版本之前的Ribbon传送门:(23条消息) 更改Ribbon负载均衡配置规则_zuodingquan666的博客-CSDN博客
1.新建配置类
package com.myrule;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
public class CustomLoadBalancerConfiguration {
@Bean
ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory){
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory
.getLazyProvider(name,ServiceInstanceListSupplier.class),name);
}
}
2.restTemplate配置
package com.cloud.config;
import com.myrule.CustomLoadBalancerConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
@LoadBalancerClient(name = "CLOUD-PROVIDER-PAYMENT",configuration = CustomLoadBalancerConfiguration.class)
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
主要实现代码:
@LoadBalancerClient(name = "CLOUD-PROVIDER-PAYMENT",configuration = CustomLoadBalancerConfiguration.class)
name里面的是:服务名
configuration:里面就是我们刚刚配置的文件名
启动项目:
运行成功
其实loadbalancer和ribbon两者之间的区别并不大,只是在写法方面有不同而已。
更多推荐
已为社区贡献9条内容
所有评论(0)