springcloud ribbon搭建服务负载均衡
2018-03-27 13:50
991 查看
加入ribbon依赖:<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>在启动器中加入:@SpringBootApplication
@EnableEurekaClient
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
在
启动eureka服务器,启动多个service
访问资源,输出端口号,会发现端口号交替出现,则测试成功
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>在启动器中加入:@SpringBootApplication
@EnableEurekaClient
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
在
RestTemplate中我们增加了一个
@LoadBalanced注解,该注解就是能够让
RestTemplate启用客户端负载均衡。
启动eureka服务器,启动多个service
访问资源,输出端口号,会发现端口号交替出现,则测试成功
直接使用Ribbon的API
另外,除了使用@LoadBalanced注解外,我们还可以直接使用Ribbon所提供的
LoadBalancerClient来实现负载均衡:
@RestController public class HelloController { protected Logger logger = LoggerFactory.getLogger(HelloController.class); @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return restTemplate.getForEntity("http://SERVICE-HELLO/hello", String.class).getBody(); } @RequestMapping(value = "/helloEx", method = RequestMethod.GET) public String helloEx() { ServiceInstance instance = this.loadBalancerClient.choose("SERVICE-HELLO"); URI helloUri = URI.create(String.format("http://%s:%s/hello", instance.getHost(), instance.getPort())); logger.info("Target service uri = 4000 {}. ", helloUri.toString()); return new RestTemplate().getForEntity(helloUri, String.class).getBody(); } }
相关文章推荐
- Spring Cloud微服务开发笔记5——Ribbon负载均衡策略规则定制
- Spring Cloud Ribbon实现客户端负载均衡的示例
- Spring Cloud 入门教程(五): Ribbon实现客户端的负载均衡
- Spring Cloud+docker实现微服务负载均衡
- 客户端负载均衡Ribbon之一:Spring Cloud Netflix负载均衡组件Ribbon介绍
- SpringCloud客户端负载均衡Ribbon
- 详解spring cloud中使用Ribbon实现客户端的软负载均衡
- SpringCloud 微服务简介及搭建(本文使用Spring封装后的API,实现负载均衡的功能)
- springcloud ribbon实现负载均衡的时候,提示Request URI does not contain a valid hostname: http://PRODUCT_SERVICE/
- 负载均衡之Spring Cloud Ribbon
- Spring Boot + Spring Cloud 构建微服务系统(二):服务消费和负载(Ribbon)
- SpringCloud | Feign如何整合Ribbon进行负载均衡的?
- spring cloud 之 客户端负载均衡Ribbon深入理解
- Spring Cloud 服务注册发现-路由-负载均衡-全链路日志跟踪-监控
- SpringCloud 笔记 (二)---- 简单搭建一个服务消费者,实现简单的ribbon负载均衡
- SpringCloud 查找调用REST服务使用RestTemplate(ribbon负载)或feign模式 教程源码 火推
- 客户端负载均衡 Spring Cloud Ribbon
- Spring Cloud 客户端负载均衡之Ribbon(三)
- 【SpringCloud】Netflix源码解析之Ribbon:负载均衡策略的定义和实现
- Spring Cloud+Eureka+Ribbon实现客户端负载均衡