java 创建一个消费者
默认简单轮询负载均衡策略 依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <parent > <artifactId > springcloud</artifactId > <groupId > com.qn</groupId > <version > 1.0-SNAPSHOT</version > </parent > <modelVersion > 4.0.0</modelVersion > <artifactId > consumer-order-ribbon</artifactId > </project >
配置 1 2 3 4 5 6 7 8 9 10 11 server : port : 8900 spring : application : name : consumer-order-ribbon eureka : client : service-url : defaultZone : http://localhost:9999/eureka instance : prefer-ip-address : true
启动类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @SpringBootApplication @EnableEurekaClient public class ConsumerApp { public static void main (String[] args) { SpringApplication.run(ConsumerApp.class ,args ) ; } @Bean @LoadBalanced public RestTemplate restTemplate () { return new RestTemplate(); } }
bean 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class User { private Long id; private Date date; public User () { } public User (Long id) { this .id = id; this .date = new Date(); } public Long getId () { return id; } public void setId (Long id) { this .id = id; } public Date getDate () { return date; } public void setDate (Date date) { this .date = date; } }
业务类 1 2 3 4 5 6 7 8 9 10 11 @RestController public class OrderController { @Autowired private RestTemplate restTemplate; @GetMapping ("/order/{id}" ) public User getOrder (@PathVariable Long id) { User user = restTemplate.getForObject("http://PROVIDER-USER/user/" + id, User.class ) ; return user; } }
测试
启动消费者(ribbon)、提供者(7900,7901)、eureka 客户端,访问如下界面刷新 10 次
两个提供者服务各被访问 5 次
自定义负载均衡策略 负载均衡策略类 1 2 3 4 5 6 7 8 9 10 11 12 @SpringBootConfiguration public class RibbonConfigration { @Bean public IRule ribbonRule () { return new RandomRule(); } }
负载均衡配置类 1 2 3 4 @RibbonClient (name = "PROVIDER-USER" , configuration = RibbonConfigration.class ) @Component public class RibbonConfig {}
测试 如上,访问 20 次,可以看到负载策略是随机访问的
配置文件的方式 1 2 3 PROVIDER-USER : ribbon : NFLoadBalancerRuleClassName : com.netflix.loadbalancer.RandomRule
此方式配置轮询策略,会优先于第二种配置类的方式。