修改默认负载均衡策略(Ribbon)

修改方式

  • 配置类
  • 配置文件

配置类 

  • 增加配置类:配置类必须拥有 @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 中增加 对应服务的个性化负载均衡策略

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


 

你可能感兴趣的:(ribbon,spring,cloud)