如果使用Eureka作为服务发现,则默认情况下加入spring-cloud-starter-netflix-eureka-client
依赖后会自动加入LoadBalance的功能,因此本文主要是分析默认情况下SpringCloud使用的负载均衡。下面以HelloWorld进入LoadBalance的世界
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
dependencies>
@SpringBootApplication
// 为了简便我们使用EurekaServer
@EnableEurekaServer
public class EurekaServeApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServeApplication.class, args);
}
}
启动server
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependencies>
spring:
application:
name: product
server:
port: ${port}
eureka:
client:
service-url:
defaultZone: http://localhost:3333/eureka/
这里product我们要起两个实例,以端口不同作为区别:5001、5002。
application-peer1.yml
port: 5001
如果是Eclipse,在启动时添加-Dspring.profiles.active=peer1
参数
application-peer2.yml
port: 5002
@RestController
@RequestMapping("/prod")
public class ProductController {
@GetMapping
public int getProduct(HttpServletRequest request) {
// 直接返回端口号以示区别
return request.getLocalPort();
}
}
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependencies>
spring:
application:
name: user
server:
port: 2222
eureka:
client:
service-url:
defaultZone: http://localhost:3333/eureka/
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
@LoadBalanced // 负载均衡
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
RestTemplate restTemplate;
@GetMapping
public void getProduct() {
// 调用Product微服务获取值
String result = restTemplate.getForObject("http://product/prod", String.class);
System.out.println(result);
}
}
所有服务都启动后,在浏览器输入http://localhost:2222/user
,按下回车键。为了看到负载均衡的效果,我们连续按下10次回车,再看下输出结果
5001
5002
5001
5002
5001
5002
5001
5002
5001
5002
从结果我们看到默认情况下是轮询这调用Product微服务,那么它是如何实现的呢?答案是通过intercept被@LoadBalanced的restTemplate的请求。
未完待续