Sentinel

官网地址:https://sentinelguard.io/zh-cn/index.html

引入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
#可获取监控信息
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-web-servlet</artifactId>
</dependency>

启动控制台

下载控制台jar包:https://github.com/alibaba/Sentinel/releases

java -Dserver.port=8333 -Dcsp.sentinel.dashboard.server=localhost:8333 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.3.jar

端口简单配置

spring.cloud.sentinel.transport.port=8719
spring.cloud.sentinel.transport.dashboard=localhost:8333

流量控制

添加流控规则
在这里插入图片描述
流控模式:链路的可以选择哪条至哪条的链路控制,关联模式B流量大可以对A进行限制。
流控效果:warm up(预热)慢慢上升到峰值。

配置流量过大提示

@Configuration
public class SeckillSentinelConfig implements BlockExceptionHandler {


    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

            R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(JSON.toJSONString(error));

    }
}

结果:

熔断降级配置

1. 使用Sentinel来保护feign远程调用

调用方的熔断保护:

@FeignClient(name = "sayService", url = "http://localhost:11111", fallback = SayServiceFallback.class, configuration = FeignConfiguration.class)
public interface SayService {

    @RequestMapping(value = "/feign/hello", method = RequestMethod.POST)
    SaySomeThing saySomeThing(@RequestBody SaySomeThing saySomeThing);
    
}
public class SayServiceFallback implements SayService {
    
    Logger logger = LoggerFactory.getLogger(SayServiceFallback.class);
    
    @Override
    public SaySomeThing saySomeThing(SaySomeThing saySomeThing) {
        SaySomeThing saySomeThingFail = new SaySomeThing();
        saySomeThingFail.setName("错误");
        saySomeThingFail.setWords("错误的话");
        logger.error("调用失败");
        return saySomeThingFail;
    }
}
@Configuration
public class FeignConfiguration {
    @Bean
    public SayServiceFallback sayServiceFallback() {
        return new SayServiceFallback();
    }    
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

2. 自定义受保护的资源

基于代码和注解的两种方式
try (Entry entry = SphU.entry("seckillSkus")) {
	//业务逻辑
} catch(Exception e) {}
@SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
    
}

// 降级调用的方法,参数必须和被调用方法一致
public List<SeckillSkuRedisTo> blockHandler(BlockException e) {

    log.error("getCurrentSeckillSkusResource被限流了,{}",e.getMessage());
    return null;

gateway网关限流

编写流控降级返回配置类

@Configuration
public class SentinelGatewayConfig {

    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //网关限流了请求,就会调用此回调
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {

                R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMessage());
                String errorJson = JSON.toJSONString(error);

                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errorJson), String.class);
                return body;
            }
        });
    }

}

版权声明:本文为weixin_43820687原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。