SpringCloud - Ribbon负载均衡
Eureka和Ribbon结合使用的时,Ribbon自动从Eureka server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例;Ribbon会自动将虚拟主机名映射到微服务的网络地址。
一. Eureka管理服务
- 启动microserver-discovery-eureka
- 启动2个或多个microserver-provider-user
- 启动microserver-consumer-movie-ribbon
1.服务集群
定义一个服务集群,将服务提供者和消费者注册到服务集群:microserver-discovery-eureka
server:port: 8761 # 指定该Eureka实例的端口eureka:client:registerWithEureka: falsefetchRegistry: falseserviceUrl:defaultZone: http://localhost:8761/eureka/
2.服务提供者
编码业务逻辑,注册到服务集群,并启动多个服务提供者:microserver-provider-user
server:port: 8000spring:application:name: microservice-provider-userjpa:generate-ddl: falseshow-sql: truehibernate:ddl-auto: nonedatasource: # 指定数据源platform: h2 # 指定数据源类型schema: classpath:schema.sql # 指定h2数据库的建表脚本data: classpath:data.sql # 指定h2数据库的数据脚本logging: # 配置日志级别,让hibernate打印出执行的SQLlevel:root: INFOorg.hibernate: INFOorg.hibernate.type.descriptor.sql.BasicBinder: TRACEorg.hibernate.type.descriptor.sql.BasicExtractor: TRACEeureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/instance:prefer-ip-address: true
java -jar microservice-provider-user-0.0.1-SNAPSHOT.jar --server.port=8000java -jar microservice-provider-user-0.0.1-SNAPSHOT.jar --server.port=8001
3.服务消费者
服务消费者注册到集群,定义Ribbon负载均衡功能,启动一个服务消费者:microserver-consumer-movie-ribbon,Ribbon可自动从Eureka server获取服务提供者列表,并基于负载均衡算法,请求其中一个服务提供者实例。
注册到集群
server:port: 8010spring:application:name: microservice-consumer-movieeureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/instance:prefer-ip-address: true
定义负载均衡的ReatTemplate
@EnableDiscoveryClient@SpringBootApplicationpublic class ConsumerMovieApplication {@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(ConsumerMovieApplication.class, args);}}
服务消费者使用负载均衡的RestTemplate访问服务提供者
@RestControllerpublic class MovieController {private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate LoadBalancerClient loadBalancerClient;@GetMapping("/user/{id}")public User findById(@PathVariable Long id) {return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);}@GetMapping("/log-user-instance")public void logUserInstance() {ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");// 打印当前选择的是哪个节点MovieController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());}}
二. 配置Ribbon负载均衡规则
1.Java配置
定义负载均衡的规则,然后设置到客户端(注意:RibbonConfiguration不能定义在@SpringBootApplication的作用范围内):
@Configurationpublic class RibbonConfiguration {@Beanpublic IRule ribbonRule() {// 负载均衡规则,改为随机return new RandomRule();}}
@Configuration@RibbonClient(name = "microservice-provider-user", configuration = RibbonConfiguration.class)public class TestConfiguration {}
2.属性配置
在application.yml中添加属性:
microservice-provider-user:ribbon:NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
三. 脱离Eureka使用Ribbon
1.去掉Eureka的依赖,修改为Ribbon,删除@EnableaDiscoveryClient注解:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-ribbon</artifactId></dependency>
2.将application.yml改为如下:
server:port: 8010spring:application:name: microservice-consumer-moviemicroservice-provider-user:ribbon:listOfServers: localhost:8000,localhost:8001
Feign超时:
feign:
client:
config:
default:
connectTimeout: 1000
readTimeout: 1000
@Bean
Request.Options feignOptions() {
return new Request.Options(/**connectTimeoutMillis**/1 * 1000, /** readTimeoutMillis **/1000 * 1000);
}