SpringBoot version: 2.7.1
SpringCloud version: 2021.0.3
project structure
Importing depends on
Eureka has been integrated with Ribbon, so you only need to import Eureka. To
replace or customize the load balancing algorithm, you need to use the interface IRule. Here we recommend the package ribbon-loadbalancer adapted to the new version of Boot and Cloud
<dependencies>
<!-- https://mvnrepository.com/artifact/com.netflix.ribbon/ribbon-loadbalancer -->
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-loadbalancer</artifactId>
<version>2.7.18</version>
</dependency>
<!--Eureka 已集成Ribbon-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<!--actuaor 完善监控信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--实体类-->
<dependency>
<groupId>com.yl</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
configuration file
server:
port: 80
spring:
application:
name: SPRINGCLOUD-CONSUMER-DEPT
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
register-with-eureka: false #不注册到eureka中
instance:
instance-id: springcloud-consumer-dept80 #描述信息
prefer-ip-address: true #优先使用ip注册,访问显示ip
management:
endpoints:
web:
exposure:
include: "*"
info:
env:
enabled: true
# 暴露端点info
info:
app.name: yl-springcloud
company.name: www.yl.com
build.artifactId: com.yl.springcloud
build.version: 1.0-SNAPSHOT
Replace load balancing algorithm
@Configuration
public class DiyRule {
@Bean
public IRule myRule(){
return new RandomRule();
}
}
There are many algorithms here, of course, you can also override the method to customize the load balancing algorithm
Main startup class, open annotation
@LoadBalancerClient(name =“SPRINGCLOUD-PROVIDER-DEPT”,configuration = DiyRule.class)
Found through the source code, just fill in the parameters according to its requirements
@SpringBootApplication
@EnableEurekaClient
@LoadBalancerClient(name ="SPRINGCLOUD-PROVIDER-DEPT",configuration = DiyRule.class)
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}