前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >hystrix熔断、降级使用示例

hystrix熔断、降级使用示例

原创
作者头像
三十而已
发布2023-02-08 12:13:21
2810
发布2023-02-08 12:13:21
举报
文章被收录于专栏:性能、容灾、后台技术专栏

详细原理介绍

参阅https://cloud.tencent.com/developer/article/2214072

一、启动类断路器注解使用

代码语言:txt
复制
@SpringCloudApplication
代替
@SpringBootApplication 
@EnableDiscoveryClient  
@EnableCircuitBreaker
image.png
image.png
代码语言:txt
复制
/**
 * 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超时熔断示例

代码语言:txt
复制
/**
  * @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降级示例

代码语言:txt
复制
/**
 * 用户服务与活动服务交互
 **/
@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 "活动备用方案--降级";
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 详细原理介绍
  • 一、启动类断路器注解使用
  • 二、HystrixCommand示例
    • 2.1 HystrixCommand超时熔断示例
      • 2.2 HystrixCommand降级示例
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档