SpringCloudHoxton.SR3版本的熔断器
SpringCloud熔断器介绍
SpringCloud 的不同的版本使用的熔断器各有不同,但目的是相同的,都是解决“雪崩效应”的方式。
⚠️:雪崩效应:一个服务调用失败,影响到后续的一连串的服务调用。例:A—>B—>C—>D—>E,如果D调用E失败,则前面的所有服务都调用失败。
SpringCloud的Hoxton.SR3版本熔断实现
1.引入熔断器依赖
<!--断路器依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2. 在启动类上添加熔断生效启动注解@EnableCircuitBreaker
@SpringCloudApplication
@EnableCircuitBreaker
public class ActivityWechatApplication {
public static void main(String[] args) {
SpringApplication.run(ActivityWechatApplication.class, args);
}
}
3. 在需要熔断的方法上添加具体的熔断方法注解@HystrixCommand
@HystrixCommand(fallbackMethod = "identifyCarVinFallback",commandKey="identifierVin")
@PostMapping("/carvinimage/identifier")
public R<IdentifyVinInfo> identifyCarVin(
@RequestBody IdentifyVinRequest request) {
if (null == request || StringUtils.isBlank(request.getImageBase64Code())) {
return R.failed500(PARAM_NULL);
}
User user = AppContextUtils.getUserNotException();
if (null == user) {
return R.failed500(USER_LOG_OUT);
}
String vin = CassIdentifyVinUtils.identifyVin(request.getImageBase64Code());
return R.ok200(inquiryService.getIdentifyVinInfo(vin, user.getCompanyId()));
}
public R<IdentifyVinInfo> identifyCarVinFallback(@RequestBody IdentifyVinRequest request){
return R.ok200(IdentifyVinInfo.builder()
.vin("")
.statusCode(HttpStatus.HTTP_INTERNAL_ERROR)
.message("VIN码解析超时")
.build());
}
此处注解中fallbackMethod调用失败后的熔断方法,commandKey是设置超时用的配置key值:需要在 application.yml 或者 bootstrap.yml 文件中增加一项配置
对应配置为:
hystrix.command.identifierVin.execution.isolation.thread.timeoutInMilliseconds: 5000 # 设置超时时间为5秒
此处配置还有另外一种方法:
@HystrixCommand(fallbackMethod = "identifyCarVinFallback",
commandProperties = @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="5000"))
@PostMapping("/carvinimage/identifier")
public R<IdentifyVinInfo> identifyCarVin(
@RequestBody IdentifyVinRequest request) {
if (null == request || StringUtils.isBlank(request.getImageBase64Code())) {
return R.failed500(PARAM_NULL);
}
User user = AppContextUtils.getUserNotException();
if (null == user) {
return R.failed500(USER_LOG_OUT);
}
String vin = CassIdentifyVinUtils.identifyVin(request.getImageBase64Code());
return R.ok200(inquiryService.getIdentifyVinInfo(vin, user.getCompanyId()));
}
public R<IdentifyVinInfo> identifyCarVinFallback(@RequestBody IdentifyVinRequest request){
return R.ok200(IdentifyVinInfo.builder()
.vin("")
.statusCode(HttpStatus.HTTP_INTERNAL_ERROR)
.message("VIN码解析超时")
.build());
}
这样就省去了在配置文件中添加配置项。