概述
准备
首先添加hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动项添加注解@SpringCloudApplication或者@EnableCircuitBreaker或者@EnableHystrix
这个注解是由SpringBoot注解:@SpringBootApplication、注册服务中心Eureka注解:@EnableDiscoveryClient、断路器注解:@EnableCircuitBreaker 三个注解集合而成
因为我已经用了@SpringBootApplication和@EnableEurekaClient所以我只添加了@EnableHystrix注解,并没有用到@SpringCloudApplication。
@EnableHystrix中引入了@EnableCircuitBreaker,但是我还不知道其区别。
如果不添加断路器的注解,hystrix是不会起作用的。
使用
使用方式有两种。
1.在方法使用
在方法上添加@HystrixCommand注解,表明方法开启hystrix
如下面例子:
/**
* 功能描述:超时降级
*
* @author 薛
* @version 1.0
* execution.timeout.enabled
* 是否开启超时,默认true
* execution.isolation.thread.timeoutInMilliseconds
* 超时时间,默认1000ms
* Fallback
* 设置当fallback降级发生时的策略
* @return
* @see com.cms.cardservice.service.CardTicketService#createOrder()
*/
@HystrixCommand(commandKey = "getCard", commandProperties = {
@HystrixProperty(name = "execution.timeout.enabled", value = "true"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
}, fallbackMethod = "getCardFallback")
public List<CardTicket> getCard() {try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<CardTicket> cards = cardTicketRepository.findAll();
return cards;
}
fallback方法:
public List<CardTicket> getCardFallback() {
return null;
}
测试结果:
1.注释掉sleep之后,成功拿到数据
2.添加sleep之后,返回fallback结果
说明Hystrix策略成功
2.在控制层使用
在类上添加注释@DefaultProperties,表明整个类开启Hystrix
defaultFallback表示统一的fallback方法
@RestController
@RequestMapping("/demo")
@DefaultProperties(defaultFallback = "defaultFallback")
public class DemoController
在方法添加注释@HystrixCommand
@HystrixCommand
@GetMapping("getCard1")
@ResponseBody
public String getCard1() {try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return "成功";
}
fallback方法
public String defaultFallback() {
return "失败";
}
返回结果
因为Hystrix的默认超时时间为1S,但是我又不想在每个方法设置超时时间
就可以在yml文件中设置默认超时时间
#default部分为更改全局的默认超时时长
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 8000
修改后的调用结果为成功,因为我只休眠了3S,超时时间已经修改为8S
最后是我所使用版本信息:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent><properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RC1</spring-cloud.version>
</properties>
Spring Boot使用2.0.6.RELEASE
Spring Cloud使用Finchley.RC1
最后
以上就是要减肥西装为你收集整理的Spring Boot 2.0.6使用hystrix降级服务的全部内容,希望文章能够帮你解决Spring Boot 2.0.6使用hystrix降级服务所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复