zl程序教程

您现在的位置是:首页 >  其它

当前栏目

hystrix熔断、降级使用示例

使用 示例 降级 Hystrix 熔断
2023-06-13 09:16:56 时间

详细原理介绍

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

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

@SpringCloudApplication
代替
@SpringBootApplication 
@EnableDiscoveryClient  
@EnableCircuitBreaker
image.png
/**
 * 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 "活动备用方案--降级";
    }
}