欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springcloud~~配置ribbon的负载均衡策略

程序员文章站 2022-06-22 19:55:16
...

配置ribbon的负载均衡策略

RoundRobinRule//轮询
RandomRule//随机
RetryRule//先按照轮询的策略获取服务,如果失败则在则定时间内会进行重试,获取可用的服务
WeightedResponseTimeRule//对轮询的扩展,相应速度越快的实例选择权重越大,越容易被选择
BestAvailableRule//会先过滤由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量小的服务
AvailabilityFilteringRule//先过滤故障实例,在选择并发量小的服务
ZoneAvoidanceRule//默认规则,符合判断server所在区域的性能和server的可用性现在服务

ribbon默认的是轮询策略RoundRobinRule

现在我们把策略改为随机RandomRule

新建model,service-consumer002

注意,spring-cloud-starter-netflix-eureka-client里面集成了ribbon,所以不用再特别的添加ribbon的依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

配置文件

server:
  port: 8202

spring:
  application:
    name: service-consumer002

eureka:
  client:
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8300/eureka/,http://localhost:8302/eureka/

自己配置负载均衡策略的话,新建的包必须不能在@ComponentScan扫描的路径下,所以我们新建配置类的时候,必须在启动类所在包以外
springcloud~~配置ribbon的负载均衡策略

在myrule包下面新建配置类

@Configuration
public class MyRule {
	@Bean
	public IRule mySelfRule(){
		return new RandomRule();//修改成随机的策略
	}
}

在主启动类所在包下面新建config包,在新建RestContextt配置类

@Configuration
public class RestContextt {
	@Bean
	@LoadBalanced//开启负载均衡
	public RestTemplate getRestTemlate(){
		return new RestTemplate();
	}
}

在新建controller包和ConsumerController类

@RestController
public class ConsumerController {
	@Value("${server.port}")
	private String port;

	private static final String URL = "http://SERVICE-PROVIDER";

	@Resource
	private RestContextt restContextt;

	@GetMapping("/consumer002")
	public String provider() {
		return restContextt.getRestTemlate().getForObject(URL + "/provider", String.class);
	}
}

在主启动类上添加注解

@SpringBootApplication
@EnableEurekaClient
//SERVICE-PROVIDER调用的服务名,configuration后面是更改的负载均衡策略的配置类
@RibbonClient(name = "SERVICE-PROVIDER", configuration = MyRule.class)
public class ServiceConsumer002 {
	public static void main(String[] args) {
		SpringApplication.run(ServiceConsumer002.class,args);
	}
}

这样就配置完成了

相关标签: springcloud ribbon