hystrix熔断、降级使用示例
使用 示例 降级 Hystrix 熔断
2023-06-13 09:16:56 时间
详细原理介绍
参阅https://cloud.tencent.com/developer/article/2214072
一、启动类断路器注解使用
@SpringCloudApplication
代替
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
/**
* SpringCloudApplication
* 提供了springboot 的功能
* 提供了自动注册到服务中心的功能
* 开启了断路器
**/
@SpringCloudApplication
public class UserApplication {
/**
* 作为Spring的一个Bean
**/
@Bean
@LoadBalanced
public RestTemplate restTemplate()
{
return new RestTemplate();
}
public static void main(String[] args) { SpringApplication.run(UserApplication.class, args);
}
}
二、HystrixCommand示例
2.1 HystrixCommand超时熔断示例
/**
* @description: 用户服务与活动服务交互
**/
@Service
public class ActivityService {
@Autowired
private RestTemplate restTemplate;
/**
* 调用活动服务,完成初次登陆,奖励发放
* 定义超时时间,让用户服务不再等待活动服务的响应
* 这样的话,可以及时释放资源。
* 使用hystrix,设置超时时间超过2s时则不继续等待调用,直接返回
**/
@HystrixCommand(commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "2000")
})
public String firstLoginTimeout(Long userId){
//使用服务名,实际上Spring会将服务名转为对应ip
return restTemplate.postForObject("http://xxx/xxxTimeout", userId, String.class);
}
}
2.2 HystrixCommand降级示例
/**
* 用户服务与活动服务交互
**/
@Service
public class ActivityService {
@Autowired
private RestTemplate restTemplate;
/**
* 需要提供一个备用方案,当活动服务不可用时,执行备用方案,即降级
**/
@HystrixCommand(fallbackMethod = "firstLoginFallback0")
public String firstLoginFallback(Long userId){
//使用服务名,实际上Spring会将服务名转为对应ip
return restTemplate.postForObject("http://xxx/xxxError", userId, String.class);
}
public String firstLoginFallback0(Long userId){
return "活动备用方案--降级";
}
}
相关文章
- Flask 学习-16.项目设计与蓝图的使用
- Ubuntu下VirtualBox使用简述
- 【Groovy】集合遍历 ( 使用集合的 findAll 方法查找集合中符合匹配条件的所有元素 | 代码示例 )
- 使用sql语句创建和删除约束示例代码
- Java连接redis的使用示例详解大数据
- 使用Jasypt来加密解密的Java示例代码详解编程语言
- 使用Redis VM实现虚拟化配置(redisvm配置)
- Oracle 视图 ALL_SUBPARTITION_TEMPLATES 官方解释,作用,如何使用详细说明
- Oracle 视图 DBA_HIER_HIER_ATTR_CLASS_AE 官方解释,作用,如何使用详细说明
- Oracle 视图 V$SQL_MONITOR_STATNAME 官方解释,作用,如何使用详细说明
- 如何快速掌握宝塔Linux使用技巧(宝塔linux使用教程)
- 使用Redis GeoAdd简化地理位置数据管理(redisgeoadd)
- 使用celery和redis提高消息队列处理效率(celery和redis)
- 了解Oracle聚集功能的原理和使用方法(oracle聚集)
- MySQL中table的概念和使用详解(mysql中table)
- Oracle中如何使用行转列查询(Oracle中行转列查询)
- Jquery事件的连接使用示例
- checkbox使用示例
- js中onload与onunload的使用示例
- 使用JS读秒使用示例
- java线程并发blockingqueue类使用示例
- java使用gzip实现文件解压缩示例
- Pythonpass语句使用示例
- 使用updatepanel局部刷新实现注册时对用户名的检测示例
- Jquery节点遍历next与nextAll方法使用示例