SpringCloud Alibaba Sentinel实现熔断与限流

目录

一、概述及安装

1、简介

2、安装

二、创建一个演示工程

1、建module

2、pom

3、yml

4、主启动

5、controller

6、测试

 7、sentinel的懒加载机制

 三、流控规则

1、流控模式

2、流控效果

 四、降级规则

1、基本介绍

2、熔断机制

3、什么是半开状态

4、降级策略实战--RT

5、降级策略实战--异常率

6、降级策略实战--异常数

五、热点key限流

1、简介

2、配置兜底方法

3、配置sentine

4、测试

5、参数例外项(高级设置)

六、@SentinelResource

1、按资源名称限流+后续处理

2、按照Url地址限流+后续处理

3、上面兜底方案面临的问题

4、客户自定义限流处理逻辑

5、一些@SentinelResource的参数

六、服务熔断功能

1、搭建测试环境

2、目的

3、什么都没配的情况下

4、配置fallback(服务降级)

 5、只配置blockHandler

 6、同时配置fallback和blockHandler

7、忽略属性.......(exceptionsToIgnore)

七、sentinel整合openFeig

1、测试环境搭建

八、各个熔断降级的比较

九、规则持久化

1、pom坐标

2、yml

3、在nacos中进行配置

 4、参数解析

5、测试


一、概述及安装

1、简介

源码地址https://github.com/alibaba/Sentinel/releases中文文档https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D就相当于之前我们讲解过的Hystrix,

 主要特性

怎么玩

官方操作文档https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring_cloud_alibaba_sentinel主要功能

服务雪崩,服务降级,服务熔断,服务限流

2、安装

  • 下载地址

Releases · alibaba/Sentinel · GitHubhttps://github.com/alibaba/Sentinel/releases

  • 下载jar包
  • 下载后运行

需安装jdk8,8080端口不能被占用

java -jar 自己的jar包

  • 运行完成后访问sentinel的控制台

登录账号密码均为sentinel

http://localhost:8080/

二、创建一个演示工程

1、建module

cloudalibaba-sentinel-service8401

2、pom

<dependencies>
    <!--SpringCloud ailibaba nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <!--SpringCloud ailibaba sentinel-datasource-nacos 后续做持久化用到-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-datasource-nacos</artifactId>
    </dependency>
    <!--SpringCloud ailibaba sentinel -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <!--openfeign-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!-- SpringBoot整合Web组件+actuator -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--日常通用jar包配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>4.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3、yml

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      server-addr: localhost:8848
    sentinel:
      transport:
        #sentinel dashboard的地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719

4、主启动

package com.xiaojiang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class SentinelServiceApplication8401 {
    public static void main(String[] args) {
        SpringApplication.run(SentinelServiceApplication8401.class,args);
    }
}

5、controller

package com.xiaojiang.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class FlowLimitController {
    @GetMapping("/testA")
    public String testA(){
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "----testA";
    }
    @GetMapping("/testB")
    public String testB(){
        return "----testB";
    }
}

6、测试

  • 打开nacos、并localhost:8848/nacos进行访问
  • 启动sentinel
  • 启动8401服务
  • 打开sentinel管理台发现

 7、sentinel的懒加载机制

需要执行一次访问即可

http://localhost:8401/testA

http://localhost:8401/testB

刷新后发现

成功 sentinel8080正在监控微服务8401

 三、流控规则

1、流控模式

单击以下按钮新增流控

  1. 直接(默认)

配置如下

表示1秒钟内查询1次就是OK,若超过次数1,就直接-快速失败,报默认错误

当短时间多次访问localhost:8401/testA,就会触发以下错误(默认)

当阈值类型选择线程,则会限制并发的数量

  • 关联

当关联的资源达到阈值时,就限流自己,当与A关联的资源B达到阀值后,就限流A自己

配置如下

postman模拟并发密集访问testB

当/testB达到阈值后,/testA会无法访问

  • 链路

2、流控效果

  • 直接->快速失败(默认的流控处理)

直接失败,抛出异常

源码:com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController

  • 预热

公式:阈值除以coldFactor(默认值为3),经过预热时长后才会达到阈值

默认coldFactor为3,即请求 QPS 从 threshold / 3 开始,经预热时长逐渐升至设定的 QPS 阈值。

官方文档https://github.com/alibaba/Sentinel/wiki/%E6%B5%81%E9%87%8F%E6%8E%A7%E5%88%B6

默认 coldFactor 为 3,即请求QPS从(threshold / 3) 开始,经多少预热时长才逐渐升至设定的 QPS 阈值。
案例,阀值为10+预热时长设置5秒。
系统初始化的阀值为10 / 3 约等于3,即阀值刚开始为3;然后过了5秒后阀值才慢慢升高恢复到10

访问/textB快速刷新,刚开始无法访问,之后就可以访问了

  • 排队等待

匀速排队,阈值必须设置为QPS

官方文档https://github.com/alibaba/Sentinel/wiki/%E6%B5%81%E9%87%8F%E6%8E%A7%E5%88%B6

 测试时发现,就算达到了阈值,也不会报错,而是一个接着一个处理请求

 四、降级规则

1、基本介绍

RT(平均响应时间,秒级)
      平均响应时间   超出阈值  且   在时间窗口内通过的请求>=5,两个条件同时满足后触发降级
      窗口期过后关闭断路器
      RT最大4900(更大的需要通过-Dcsp.sentinel.statistic.max.rt=XXXX才能生效)
 
异常比列(秒级)
    QPS >= 5 且异常比例(秒级统计)超过阈值时,触发降级;时间窗口结束后,关闭降级
 
异常数(分钟级)
     异常数(分钟统计)超过阈值时,触发降级;时间窗口结束后,关闭降级

2、熔断机制

Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,
让请求快速失败,避免影响到其它的资源而导致级联错误。
 
当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException)。

Sentinel的断路器是没有半开状态的

3、什么是半开状态

半开的状态系统自动去检测是否请求有异常,
没有异常就关闭断路器恢复使用,
有异常则继续打开断路器不可用。具体可以参考Hystrix

4、降级策略实战--RT

  • 简介

  • 测试

测试代码

@GetMapping("/testD")
public String testD()
{
    //暂停几秒钟线程
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
    log.info("testD 测试RT");
    return "------testD";
}

 配置

jmeter压测

新建一个线程组

启动

  • 结论

我们希望200毫秒处理完本次任务,
如果超过200毫秒还没处理完,在未来1秒钟的时间窗口内,断路器打开(保险丝跳闸)微服务不可用,保险丝跳闸断电了
 
后续我停止jmeter,没有这么大的访问量了,断路器关闭(保险丝恢复),微服务恢复OK

可以看到平均RT为1000

5、降级策略实战--异常率

  • 介绍

 

  •  测试代码
@GetMapping("/testB")
public String testB()
{
    log.info("testB 测试异常率");
    int age = 10/0;
    return "------testB";
}
  • 配置

  • jmeter压测

配置与上面一致

  • 结论

按照上述配置,
单独访问一次,必然来一次报错一次(int age  = 10/0),调一次错一次;
 
开启jmeter后,直接高并发发送请求,多次调用达到我们的配置条件了。
断路器开启(保险丝跳闸),微服务不可用了,不再报错error而是服务降级了。

6、降级策略实战--异常数

  • 介绍

异常数是按照分钟统计的

时间窗口一定要大于等于60秒。

 

测试代码与上面一致

配置

  • 结论

当访问/testB的第十次后,触发熔断,在窗口时间内无法访问

五、热点key限流

1、简介

  • 何为热点

热点即经常访问的数据,很多时候我们希望统计或者限制某个热点数据中访问频次最高的TopN数据,并对其访问进行限流或者其它操作

  • 官方文档

https://github.com/alibaba/Sentinel/wiki/%E7%83%AD%E7%82%B9%E5%8F%82%E6%95%B0%E9%99%90%E6%B5%81

  • 兜底方法

分为系统默认和客户自定义,两种
 
之前的case,限流出问题后,都是用sentinel系统默认的提示:Blocked by Sentinel (flow limiting)
 
我们能不能自定?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?

2、配置兜底方法

 @GetMapping("/testHotKey")
    //相当于Hystrix的@HystrixCommand
    @SentinelResource(value = "testHotKey" , blockHandler = "dealHandler")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
                             @RequestParam(value = "p2",required = false) String p2){
        return "----testHotKey";
    }
    //自定义的兜底方法
    public String dealHandler(String p1,String p2 , BlockException exception){
        return "-----dealHandler_testHotKey";
    }

3、配置sentine

限流模式只支持QPS模式,固定写死了。(这才叫热点)

@SentinelResource注解的方法参数索引,0代表第一个参数,1代表第二个参数,以此类推
单机阀值以及统计窗口时长表示在此窗口时间超过阀值就限流。


上面的抓图就是第一个参数有值的话,1秒的QPS为1,超过就限流,限流后调用dealHandler_testHotKey支持方法。

4、测试

sentinel只会监控p1的访问次数,对p2不监控

http://localhost:8401/testHotKey?p1=4,访问频率超过设定的阈值,就会调用自己设置的兜底函数。

5、参数例外项(高级设置)

我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样

假如当p1的值等于3时,它的阈值可以达到200

  • 测试

http://localhost:8401/testHotKey?p1=3 ,时阈值为200

http://localhost:8401/testHotKey?p1=4,时阈值为1

  • 注意

热点参数的注意点,参数必须是基本类型或者String

六、@SentinelResource

1、按资源名称限流+后续处理

  • controller
@GetMapping("/testHotKey")
    //相当于Hystrix的@HystrixCommand
    @SentinelResource(value = "testHotKey" , blockHandler = "dealHandler")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
                             @RequestParam(value = "p2",required = false) String p2){
        return "----testHotKey";
    }
    //自定义的兜底方法
    public String dealHandler(String p1,String p2 , BlockException exception){
        return "-----dealHandler_testHotKey";
    }

配置关系

表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流

2、按照Url地址限流+后续处理

如果按URL地址限流则会调用系统自定义的兜底方法

3、上面兜底方案面临的问题

1    系统默认的,没有体现我们自己的业务要求。
 
2  依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。
 
3  每个业务方法都添加一个兜底的,那代码膨胀加剧。
 
4  全局统一的处理方法没有体现。

4、客户自定义限流处理逻辑

  • 创建CustomerBlockHandler类用于自定义限流处理逻辑

  •  配置CustomerBlockHandler类
package com.xiaojiang.myHandler;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;

public class CustomerBlockHandler {
    //方法需是静态的
    public static CommonResult handleException1(BlockException exception)
    {
        return new CommonResult(4441,"用户自定义的兜底方法"+exception.getClass().getCanonicalName()+"\t 服务不可用");
    }
    public static CommonResult handleException2(BlockException exception)
    {
        return new CommonResult(4442,"用户自定义的兜底方法"+exception.getClass().getCanonicalName()+"\t 服务不可用");
    }
}
  • 在controller中的配置

@SentinelResource(value = "byResource",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handleException1")

//produces:指定返回的数据类型是json
@GetMapping(value = "/byResource",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "byResource",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handleException1")
    public CommonResult byResource()
    {
        return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
    }

  • sentinel中的配置

  •  测试

5、一些@SentinelResource的参数

六、服务熔断功能

1、搭建测试环境

  • 新建服务提供端9003/9004

建模块

新建cloudalibaba-provider-payment9003模块

pom

<dependencies>
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!--SpringCloud ailibaba nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <!-- SpringBoot整合Web组件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--日常通用jar包配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

yml

server:
  port: 9003

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'

主启动

package com.xiaojiang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class AlibabaProviderApplication9003 {
    public static void main(String[] args) {
        SpringApplication.run(AlibabaProviderApplication9003.class,args);
    }
}

controller

package com.xiaojiang.controller;

import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class PaymentController {
    @Value("${server.port}")
    private String serverPort;

    public static HashMap<Long,Payment> hashMap = new HashMap<>();
    static
    {
        hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
        hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
        hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
    }

    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
    {
        Payment payment = hashMap.get(id);
        CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort:  "+serverPort,payment);
        return result;
    }

}

9004与9003相同,只需改一下端口即可

  • 消费端

建模块

cloudalibaba-consumer-nacos-order84

pom

<dependencies>
    <!--SpringCloud ailibaba nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <!--SpringCloud ailibaba sentinel -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!-- SpringBoot整合Web组件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--日常通用jar包配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

yml

server:
  port: 84

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719


#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider


主启动

package com.xiaojiang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosOrder84 {
    public static void main(String[] args) {
        SpringApplication.run(NacosOrder84.class,args);
    }
}

conf

package com.xiaojiang.conf;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

controller

package com.xiaojiang.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/fallback/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "fallback" )
    public CommonResult<Payment> fallback1(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }
}

2、目的

fallback管运行异常

blockHandler管配置违规

3、什么都没配的情况下

测试地址http://localhost:84/consumer/fallback/1正常

http:localhost:84/consumer/fallback/4

返回error page,不友好

4、配置fallback(服务降级)

package com.xiaojiang.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/fallback/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "fallback" , fallback = "handlerFallback")
    public CommonResult<Payment> fallback1(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }
    public CommonResult<Payment> handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,"null");
        return new CommonResult<Payment>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }
}

结果

说明

 5、只配置blockHandler

package com.xiaojiang.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/fallback/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "fallback", blockHandler = "blockHandler")
    public CommonResult<Payment> fallback1(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }

    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

}

 配置一下sentinel

结果

 6、同时配置fallback和blockHandler

package com.xiaojiang.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/fallback/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "fallback" , fallback = "handlerFallback",
                        blockHandler = "blockHandler")
    public CommonResult<Payment> fallback1(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }
    public CommonResult<Payment> handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,"null");
        return new CommonResult<Payment>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }
    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

}

 在sentinel中进行配置

结果

若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。

7、忽略属性.......(exceptionsToIgnore)

package com.xiaojiang.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.comsumer.entities.CommonResult;
import com.example.comsumer.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/fallback/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @SentinelResource(value = "fallback" , fallback = "handlerFallback",
                        blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback1(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }
    public CommonResult<Payment> handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,"null");
        return new CommonResult<Payment>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }
    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

}

结果

七、sentinel整合openFeig

1、测试环境搭建

修改84模块

pom添加以下坐标

<!--SpringCloud openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>

yml

# 激活Sentinel对Feign的支持
feign:
  sentinel:
    enabled: true

新建一个service包,创建带@FeignClient注解的业务接口
 

package com.atguigu.springcloud.alibaba.service;

import com.atguigu.springcloud.alibaba.entities.CommonResult;
import com.atguigu.springcloud.alibaba.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @auther zzyy
 * @create 2019-12-10 17:17
 * 使用 fallback 方式是无法获取异常信息的,
 * 如果想要获取异常信息,可以使用 fallbackFactory参数
 */
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)//调用中关闭9003服务提供者
public interface PaymentService
{
    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}

用PaymentFallbackService实现这个接口

 
package com.atguigu.springcloud.alibaba.service;

import com.atguigu.springcloud.alibaba.entities.CommonResult;
import com.atguigu.springcloud.alibaba.entities.Payment;
import org.springframework.stereotype.Component;

/**
 * @auther zzyy
 * @create 2019-12-10 17:18
 */
@Component
public class PaymentFallbackService implements PaymentService
{
    @Override
    public CommonResult<Payment> paymentSQL(Long id)
    {
        return new CommonResult<>(444,"服务降级返回,没有该流水信息",new Payment(id, "errorSerial......"));
    }
}
 
 
 
 

controller添加以下代码

//==================OpenFeign
    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/openfeign/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
    {
        if(id == 4)
        {
            throw new RuntimeException("id");
        }
        return paymentService.paymentSQL(id);
    }

主启动

 
package com.atguigu.springcloud.alibaba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @auther zzyy
 * @create 2020-02-13 20:22
 */
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84
{
    public static void main(String[] args) {
            SpringApplication.run(OrderNacosMain84.class, args);
    }
}
 
 

测试时如果将服务提供者9003单机则服务降级调用PaymentFallbackService.class


八、各个熔断降级的比较

九、规则持久化

在模块8401下完成

1、pom坐标

<!--SpringCloud ailibaba sentinel-datasource-nacos 后续做持久化用到-->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

2、yml

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      server-addr: localhost:8848
    sentinel:
      transport:
        #sentinel dashboard的地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            //对应的是nacos中的dataId
            dataId: ${spring.application.name}
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

3、在nacos中进行配置

 4、参数解析

resource:资源名称;
limitApp:来源应用;
grade:阈值类型,0表示线程数,1表示QPS;
count:单机阈值;
strategy:流控模式,0表示直接,1表示关联,2表示链路;
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
clusterMode:是否集群。

5、测试

启动8401后刷新sentinel发现业务规则有了

快速访问8401/rateLimit/byUrl

出现默认的兜底方法

在重启8401后sentinel中的规则还在

sentinel持久化完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值