首页 > 代码库 > 003客户端负载均衡Ribbon & 短路器Hystrix
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。