修改方式
- 配置类
- 配置文件
配置类
- 增加配置类:配置类必须拥有 @Configuration 且不能在 @ComponentScan 包下
package com.learning.springcloud.config;
import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RibbonConfig {
/**
* 全局设置负载均衡策略
*
* @return
*/
@Bean
public IRule iRule() {
return new NacosRule();
}
}
- 增加客户端负载配置 @RibbonClients
package com.learning.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@RibbonClients(value = {@RibbonClient(name = "stock-service", configuration = com.learning.springcloud.config.RibbonConfig.class)
})
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class); }
@Bean
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
}
配置文件
-
注释启动类上 @RibbonClien
-
applicaiton.yml 中增加 对应服务的个性化负载均衡策略文章来源:https://www.toymoban.com/news/detail-792752.html
server:
port: 8030spring:
application:
name: order-service
cloud:
nacos:
server-addr: 127.0.0.1:8847
discovery:
username: nacos
password: nacos
namespace: 5fe640ca-1ed2-496c-97bd-e0bfb7aef639
stock-service: # 服务名称
ribbon:
NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule
文章来源地址https://www.toymoban.com/news/detail-792752.html
到了这里,关于修改默认负载均衡策略(Ribbon)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!