003客户端负载均衡Ribbon & 短路器Hystrix
Posted TBBS
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了003客户端负载均衡Ribbon & 短路器Hystrix相关的知识,希望对你有一定的参考价值。
1、POM配置
和普通Spring Boot工程相比,仅仅添加了Eureka、Ribbon、Hystrix、Spring Boot Starter Actuator依赖和Spring Cloud依赖管理
<dependencies> <!--添加Eureka Server依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 负载均衡ribbon --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <!-- 断路器Hystrix --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <!-- 服务健康检测 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <!--Spring Cloud依赖版本管理--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
02、使能Eureka Client
@SpringBootApplication @EnableEurekaClient //使能Eureka客户端 @EnableCircuitBreaker //使能断路器 public class RibbonApplication { @Bean @LoadBalanced //负载均衡的RestTemplate public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(RibbonApplication.class, args); } }
03、src/main/resources工程配置文件application.yml
server:
port: 3001 #默认启动端口
spring:
application:
name: ribbon-hello-service-consumer #应用名,请在hosts中添加映射
eureka:
instance:
hostname: ribbon-hello-service-consumer #主机名
preferIpAddress: true #使用IP注册
client:
serviceUrl:
defaultZone: http://localhost:1000/eureka/ #服务注册中心地址
04、负载均衡消费
@Service public class HelloConsumerService { @Autowired private RestTemplate restTemplate; // 负载均衡消费 @HystrixCommand(fallbackMethod = "fallback") public String hello() { return this.restTemplate.getForObject("http://hello-service-provider/hello/", String.class); } //短路器打开时,执行此函数 public String fallback() { return "Error"; } }
05、测试使用服务
@RestController public class HelloController { @Autowired private HelloConsumerService helloService; @GetMapping("/hello") public String hello() { return this.helloService.hello(); } }
以上是关于003客户端负载均衡Ribbon & 短路器Hystrix的主要内容,如果未能解决你的问题,请参考以下文章