<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.9.RELEASEversion>
parent>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.SR10version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
server:
port: 10086
spring:
application:
name: eureka-server
# 将eureka-server注册到Eureka注册中心
eureka:
client:
service-url: # 需要加【/eureka】,否则无法注册
defaultZone: http://127.0.0.1:10086/eureka
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
server:
port: 8080
spring:
application:
name: order-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
server:
port: 8081
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
使用服务名,根据负载均衡规则挑选服务提供者
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
// String url = "http://localhost:8081/user/" + order.getUserId(); // 硬编码
// 根据服务名从 Eureka 注册中心中获取服务的IP和端口号
String url = "http://user-service/user/" + order.getUserId();
LoadBalancerInterceptor 会拦截被 @LoadBalanced 注解标注的 RestTemplate 发起的请求。它实现了 ClientHttpRequestInterceptor 接口,该接口作用:拦截客户端HTTP请求。LoadBalancerInterceptor 的 intercept 方法中获取服务名称,把服务名称交给 RibbonLoadBalanceClient,RibbonLoadBalanceClient 把服务名称交给 DynamicServerListLoadBalancer,DynamicServerListLoadBalancer 从 Eureka 注册中心获取该服务名的所有的实例信息,然后根据负载均衡规则挑选一个服务实例(chooseServer
)。负载均衡规则由 IRule 接口指定,IRule 的实现类有:RoundRobinRule(轮询)、RetryRule、RandomRule(随机)
@Bean
public IRule iRule() {
return new RandomRule();
}
user-service:
ribbon: # user-service的负载均衡规则是:随机
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
ribbon:
eager-load:
enabled: true # 饥饿创建负载均衡客户端RibbonLoadBalanceClient
clients: user-service # 指定对user-service服务执行饥饿加载
RibbonLoadBalanceClient 默认是懒创建,首次访问的时候才创建(首次请求响应时间会比较长)。
饥饿加载:项目创建的时候就创建 RibbonLoadBalanceClient