Sentinel备忘

Sentinel主要有四个功能:

1.流量控制,实现步骤:

a.在控制台的“流控规则”或“簇点链路”中 新增“流控规则”,资源名写除域名外路径,单机阈值设每秒访问次数即可。

b.自定义控制消息方法:引入依赖:

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-spring-webmvc-adapter</artifactId>
</dependency>

新建配置类:

@Configuration
public class SearchSentinelConfig implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        DataGridView dataView = new DataGridView();
        dataView.setMsg(SentinelConstant.REQUEST_TOO_MANY);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(dataView));
    }
}

2.调用方的熔断保护

a.加入配置: feign.sentinel.enabled=true

b.在调用方针对一个feign接口写一个实现类,即可实现当远程接口宕机时,自动调用fallback方法,防止页面出错:

@Slf4j
@Component
public class InfoFeignServiceFallback implements InfoFeignService {

    
@GetMapping(value = "getlistpager/fallback")//注意加这个,跟原方法中区分开,否则报错。
    public R getListPager(String tables, String whereOrder, int page, int size) {
        return R;
    } 

}

c.另一种方法:在调用方手动指定一个降级策略。

3.自定义受保护的代码块或方法,即可在控制台看到相关资源。

a)代码:使用try(){}catch(){}

List<Doc> tuiCate = null;
try (Entry entry = SphU.entry("tuicode")) {
    tuiCate = docMapper.getCateTopTui(n, bid, sid);
} catch (BlockException be) {
    log.error("这是被保护的资源:tuicode");
}

b)方法:

public List<Doc> smallCateHandler(BlockException blockException){
    log.error("smallCateHandler 被限流了。");
    return null;
}
@SentinelResource(value = "smallcateresource",blockHandler = "smallCateHandler")
public List<Doc> getSmallCates(Integer bid) {。。。}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值