Sentinel-只做降级(异常降级)

1.引入依赖
<dependency>
 <groupId>com.alibaba.csp</groupId>
 <artifactId>sentinel-annotation-aspectj</artifactId>
 <version>1.8.1</version>
</dependency>

2.注入Bean

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Slf4j
@Configuration
public class SentinelAspectConfiguration {
 
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

3.采用注解方式

/**
 * 降级结果也会缓存
 * @return
 */
@Override
@Cacheable(value = {"cache_1min"}, keyGenerator = "customKeyGenerator")
@SentinelResource(value = "sentinelLowerLevelTest",fallback = "helloFallback")
public String sentinelLowerLevelTest() {
    Random random = new Random();
    int number = random.nextInt(10);
    if(number > 4){
        throw new RuntimeException("系统异常测试");
    }
    return String.format("success:%s",number);
}
 
// Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
public String helloFallback(Throwable e) {
    return String.format("success:降级结果:"+e.getMessage());
}

备注:@Cacheable 是Spring的缓存(org.springframework.cache.annotation.Cacheable);如果出现异常降级,降级结果也会走缓存策略(跟未发生异常时表现一致);

4.官方文档:https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值