yaml :
hystrix:
threadpool.default.coreSize: 10 #包裹默认的线程池 command.default.execution.isolation.thread.timeoutInMilliseconds: 60000 #熔断超时(yaml配置文件信息)
//方法上添加注解
@HystrixCommand(fallbackMethod = “queryerror”)
//回调方法
public ResponseObj queryerror(NewUserDTO userDTO, BindingResult bindingResult, Throwable e) {
log.error(“获取新人列表接口 熔断,NewUserDTO:{},错误信息:{}”, userDTO.toString(), e);
return new ResponseObj(Constant.RESPONSE_ERROR_KEY_CODE1000, “该服务暂时无法访问”, “”);
}
注意点:
1.方法注解的方法名和回调方法名一致
2.方法上的参数要和回调方法参数相同
实例:
@HystrixCommand(fallbackMethod = "userManagerError")
@ApiOperation("保存用户")
@JsonPostMapping("/newUser")
public ResponseResult saveUser(@RequestBody UserReq req){
ResponseResult responseResult=new ResponseResult();
try {
LOGGER.info("保存用户入参req:" + JSON.toJSONString(req));
User user = transSaveUser(req);
boolean flg = userService.saveUser(user);
if(flg){
responseResult.setRespCode(ResponseResult.CODE_SUCCESS);
responseResult.setRespMsg("保存成功");
} else {
responseResult.setRespCode(ResponseResult.CODE_BUSIERR);
responseResult.setRespMsg("用户账号已存在或者保存异常");
}
LOGGER.info("保存用户出参resp:" + JSON.toJSONString(responseResult));
} catch (Exception e) {
LOGGER.error("保存用户异常:", e);
responseResult.setRespCode(ResponseResult.CODE_SYSERR);
responseResult.setRespMsg("系统异常");
}
return responseResult;
}
回调方法:
public ResponseResult userManagerError(UserReq userReq) {
LOGGER.error("获取用户管理接口 熔断,NewUserDTO:{},错误信息:{}", userReq.toString());
ResponseResult responseResult = new ResponseResult();
responseResult.setRespCode(ResponseResult.CODE_SYSERR);
responseResult.setRespMsg("该服务暂时无法访问");
return responseResult;
}
启动类加入@EnableHystrixDashboard注解:
@SpringCloudApplication
@EnableHystrixDashboard
@ComponentScan(basePackages = {"com.cntaiping.gaimarketapp"})
@EnableDiscoveryClient
public class ManageRun {
public static void main(String[] args) {
SpringApplication.run(ManageRun.class, args);
}
}