继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Sentinel(2)

fox鑫
关注TA
已关注
手记 19
粉丝 0
获赞 1

控制台相关配置:


在代码中配置Sentinel

定义一个资源名为test-sentinel-api的sentinel资源,当资源被降级或者被限流,会返回对应的字段

所定义的方法,返回值和入参需要一致

    @GetMapping("/test-sentinel-Resource")
    @SentinelResource(value = "test-sentinel-api"
            ,blockHandler = "block"
            ,fallback = "fallback"
            ,blockHandlerClass = TestControllerBlockHandlerClass.class)
    public String testSentinelResource(@RequestParam(required = false) String a){
        Entry entry = null;
        //被保护的逻辑
        if (StringUtils.isBlank(a)){
            throw new IllegalArgumentException("a cannot be null");
        }
            return a;
    }

    /**
     * 1.5:处理降级
     * sentinel1.6后,可以处理Throwable,任何异常都可以走到这里
     * @param a
     * @return
     */
    public String fallback( String a){
        log.warn("降级了fallback");
        return "降级了fallback";
    }
}

package com.itmuch.usercenter.sentineltest;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestControllerBlockHandlerClass {
    /**
     * 处理限流或者降级
     * @param a
     * @param e
     * @return
     */
    public static String block(String a , BlockException e) {
        log.warn("限流,或则被降级了block",e);
        return "限流,或则被降级了block";
    }


}

restTemplate整合sentinel

现在配置文件中开启整合sentinel

resttemplate:
  sentinel:
    enabled: true #开启/关闭@SentinelRestTemplate注解

在启动文件中的restTemplate的bean中添加注解@SentinelRestTemplate

public class ContentCenterApplication {

    public static void main(String[] args) {
        SpringApplication.run(ContentCenterApplication.class, args);
    }

    //在spring容器中,创建一个对象,其类型为RestTemplate,名称&ID为restTemplate
    //<bean id="restTemplate" class="xxx.RestTemplate"/>
    @Bean
    @LoadBalanced//为restTemplate整合Ribbon
    @SentinelRestTemplate //为restTemplate整合sentinel
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

进入@SentinelRestTemplate注解中可以配置错误信息

http://img2.mukewang.com/60f178240001458c19201039.jpg

@SentinelResource

使用方式类似

http://img4.mukewang.com/60f178c70001a7d919201039.jpg

feign整合sentinel

先在配置文件中开启整合sentinel(没有提示)

feign:
  sentinel:
    enabled: true #feign整合sentinel


在feign调用的接口中,配置sentinel类

fallback:发生限流或降级会触发逻辑,但不会返回错误信息;

fallbackfactory:发生限流或降级会触发逻辑,并返回错误信息;

http://img3.mukewang.com/60f17623000169ee19201039.jpg

http://img4.mukewang.com/60f176730001761019201039.jpg

http://img2.mukewang.com/60f1767e0001b09b19201039.jpg

这里流控规则设置限流

http://img4.mukewang.com/60f176950001000e10600543.jpg

触发后

http://img3.mukewang.com/60f176b1000118bf07340580.jpg


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP