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