SpringCloud Day12---SpringCloud Alibaba Sentinel 服务熔断与限流(三)

简介: SpringCloud Day12---SpringCloud Alibaba Sentinel 服务熔断与限流(三)

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


通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息


  • 业务类RateLimitController:
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
    return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
  • 配置:


436337162ee8e45b5fca5d2336657af8.png


  • 测试

疯狂点击http://localhost:8401/rateLimit/byUrl

会返回Sentinel自带的限流处理结果


5a0a140a2355b68aea59506b55dc1cb0.png


15.8.3 上面兜底方案面临的问题


1 系统默认的,没有体现我们自己的业务要求。

2 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。


3 每个业务方法都添加一个兜底的,那代码膨胀加剧。

4 全局统一的处理方法没有体现。


15.8.4 客户自定义限流处理逻辑


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


public class CustomerBlockHandler
{
    public static CommonResult handleException(BlockException exception){
        return new CommonResult(2020,"自定义的限流处理信息......CustomerBlockHandler");
    }
}

dcaa29bb5ac21b98218683437a27b995.png



  • 修改RateLimitController
  /**
     * 自定义通用的限流处理逻辑,
     blockHandlerClass = CustomerBlockHandler.class
     blockHandler = handleException2
     上述配置:找CustomerBlockHandler类里的handleException2方法进行兜底处理
     */
  /**
     * 自定义通用的限流处理逻辑
     */
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
                  blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2")
public CommonResult customerBlockHandler()
{
    return new CommonResult(200,"按客户自定义限流处理逻辑");
}


  • Sentinel控制台配置:



160369c4b3fb4409bb2ab926ac767b0e.png

  • 测试:

疯狂访问:http://localhost:8401/rateLimit/customerBlockHandler ,测试后我们自定义的出来了.

  • 进一步说明


ca477e89d1b7e79badd650bd75acf475.png


15.8.5 更多注解属性说明


34b9fd30dee5f4fc0c9c9547bcd8e902.png

1.Sentinel主要有三个核心Api

  • SphU定义资源
  • Tracer定义统计
  • ContextUtil定义了上下文

2.自定义Resource

7697415fbdd7c76baff29cb6bdde2dcd.png



所有的代码都要用try-catch-finally方式进行处理,o(╥﹏╥)o


15.9 服务熔断功能


15.9.1 sentinel整合+Ribbon+fallback


1.启动nacos和sentinel

2.构建提供者9003/9004

  • 建Module—cloudalibaba-provider-payment9003/9004
  • POM


<dependencies>
    <!--SpringCloud ailibaba nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <groupId>com.rg.springcloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</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: 9003
spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.174.128:8848 #配置Nacos地址
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 主启动
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{
    public static void main(String[] args) {
            SpringApplication.run(PaymentMain9003.class, args);
    }
}

业务类

@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;
    }
}
  • 测试地址:http://localhost:9003/paymentSQL/1 ,可以正常访问


3.消费者84


  • 建Module—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>com.rg.springcloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</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: 192.168.174.128:8848
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8888
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
##消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider
  • 主启动


@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84
{
    public static void main(String[] args) {
            SpringApplication.run(OrderNacosMain84.class, args);
    }
}
  • 业务类

ApplicationContextConfig

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

4.CircleBreakerController +测试

目的:验证fallback管运行异常,blockHandler管配置违规

  • 编写基础代码


@RestController
@Slf4j
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback") 
  public CommonResult <Payment> fallback(@PathVariable Long id){
        CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if(id==4){
            System.out.println("44444444444");
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常...");
        }else if(result.getData()==null){
            System.out.println("111111111111111");
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常...");
        }
        return result;
    }
}


访问: http://localhost:84/consumer/fallback/1 进行测试,测试成功! 访问 http://localhost:84/consumer/fallback/4 跳转至到错误页面.但是这个error页面对用户很不友好

只配置fallback


编码:

@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常
public CommonResult <Payment> fallback(@PathVariable Long id){
    CommonResult 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 handlerFallback(@PathVariable Long id,Throwable e){
    Payment payment = new Payment(id, "null");
    return new CommonResult(444, "兜底异常handlerFallback,exception内容:" + e.getMessage(), payment);
}

结果:


2f01ebc1a52b4963efe9280cdb6ad88d.png

9c611b208f6cdc4ebc074806a320f3c1.png

e4099dc4fede98fe039e074e1f87a3de.png

图说:


373008a2d0b1625b90963919c49190f6.png


  • 只配置blockHandler


编码:


@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常
@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流
public CommonResult <Payment> fallback(@PathVariable Long id){
    CommonResult 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 handlerFallback(@PathVariable Long id,Throwable e){
    Payment payment = new Payment(id, "null");
    return new CommonResult(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需配置:


f3443dca86e21fbae24e238e820d27bd.png


异常超过2次后,断路器打开,断电跳闸,系统被保护


结果:


d52b41c481094f316af653b9bf524a9b.png


图说:


5a4ad3bc0a27a4665e82e95511dab641.png

  • fallback和blockHandler都配置


编码:


@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback")
//@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
public CommonResult <Payment> fallback(@PathVariable Long id){
    CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
    if(id==4){
        System.out.println("44444444444");
        throw new IllegalArgumentException("IllegalArgumentException,非法参数异常...");
    }else if(result.getData()==null){
        System.out.println("111111111111111");
        throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常...");
    }
    return result;
}
public CommonResult handlerFallback(@PathVariable Long id,Throwable e){
    Payment payment = new Payment(id, "null");
    return new CommonResult(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需配置:241fb9b81a8510ca4eb4b447cbda2f50.png

结果:


9fa0bfc703528482d6434464fa312a9b.png


若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。如果没有超出限流规则,则走fallback 逻辑.


图说:

2473886e7061a86c7f562b5121ba615d.png

  • 忽略属性—exceptionsToIgnore


编码:

@RequestMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback")
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult <Payment> fallback(@PathVariable Long id){
        CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if(id==4){
            System.out.println("44444444444");
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常...");
        }else if(result.getData()==null){
            System.out.println("111111111111111");
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常...");
        }
        return result;
    }
    public CommonResult handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id, "null");
        return new CommonResult(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无配置


图说:


67960b56841aa249af9ffd2db9da5601.png

结果: 程序异常打到前台了,对用户不友好

f40ad227f369197e99d7a48491a3a826.png



15.9.2 sentinel整合+Feign+fallback


1.修改84模块:84消费者调用提供者9003,Feign组件一般是消费侧


2.修改代码


  • POM
<!--SpringCloud openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • YML—激活Sentinel对Feign的支持
server:
  port: 84
spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.174.128:8848
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8888
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
##消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider
# 激活Sentinel对Feign的支持
management:
  endpoints:
    web:
      exposure:
        include: '*'
feign:
  sentinel:
    enabled: true
  • 业务类

带@FeignClient注解的业务接口


@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类

@Component
public class PaymentFallbackService implements PaymentService
{
    @Override
    public CommonResult<Payment> paymentSQL(Long id)
    {
        return new CommonResult<>(444,"服务降级返回,没有该流水信息",new Payment(id, "errorSerial......"));
    }
}

controller

@RestController
@Slf4j
public class CircleBreakerController
{
//========================Sentinel结合OpenFeign
@Resource
private PaymentService paymentService;
    @GetMapping(value = "/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        // if(id==4){
        //     throw new RuntimeException("没有该id");
        // }
        return paymentService.paymentSQL(id);
    }
}
  • 主启动—添加@EnableFeignClients启动Feign的功能


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

3.测试


访问: http://localhost:84/consumer/paymentSQL/1

测试84调用9003,此时故意关闭9003微服务提供者,可以看到84消费侧自动降级,不会被耗死


15.9.3 熔断框架比较

670847afc50f572bde3e1a086eb99e70.png


15.10 规则持久化


15.10.1 是什么


一旦我们重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化


15.10.2 怎么玩


将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上sentinel上的流控规则持续有效


15.10.3 实现步骤


  • 修改cloudalibaba-sentinel-service8401
  • POM
<!--SpringCloud ailibaba sentinel-datasource-nacos -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
  • YML—添加Nacos数据源配置



48df99fd1d49ff64ee6bbe33b3105465.png

添加Nacos业务规则配置

284e6871436adc3da7d4eb67d98ef970.png


内容解析:


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

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


daa619c4c215836328fb0ec80fea57f7.png


15.10.4 测试


  • 快速访问测试接口,http://localhost:8401/rateLimit/byUrl ,显示: Blocked By Sentinel(flow limiting)错误 ,说明配置文件生效了
  • 停止8401再看sentinel


网络异常,图片无法展示
|



重新启动8401再看sentinel .


乍一看还是没有,稍等一会儿.多次调用 http://localhost:8401/rateLimit/byUrl 重新配置出现了,持久化验证通过

相关文章
|
2月前
|
监控 Java Sentinel
使用Sentinel进行服务调用的熔断和限流管理(SpringCloud2023实战)
Sentinel是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
80 3
|
27天前
|
监控 Dubbo 应用服务中间件
通用快照方案问题之Sentinel与SpringCloud和Dubbo的整合如何解决
通用快照方案问题之Sentinel与SpringCloud和Dubbo的整合如何解决
30 0
|
30天前
|
监控 算法 Java
高并发架构设计三大利器:缓存、限流和降级问题之配置Sentinel的流量控制规则问题如何解决
高并发架构设计三大利器:缓存、限流和降级问题之配置Sentinel的流量控制规则问题如何解决
|
2月前
|
自然语言处理 监控 开发者
springCloud之Sentinel流量路由、流量控制、流量整形、熔断降级
springCloud之Sentinel流量路由、流量控制、流量整形、熔断降级
38 0
|
1月前
|
监控 Java 应用服务中间件
SpringCloud面试之流量控制组件Sentinel详解
SpringCloud面试之流量控制组件Sentinel详解
99 0
|
2月前
|
Java 开发者 Sentinel
Spring Cloud系列——使用Sentinel进行微服务保护
Spring Cloud系列——使用Sentinel进行微服务保护
45 5
|
2月前
|
监控 Java API
深入解析 Spring Cloud Sentinel:分布式系统流量控制与熔断降级的全面指南
深入解析 Spring Cloud Sentinel:分布式系统流量控制与熔断降级的全面指南
60 0
深入解析 Spring Cloud Sentinel:分布式系统流量控制与熔断降级的全面指南
|
3月前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
|
3月前
|
监控 Java Sentinel
Spring Cloud Sentinel:概念与实战应用
【4月更文挑战第28天】在分布式微服务架构中,确保系统的稳定性和可靠性至关重要。Spring Cloud Sentinel 为微服务提供流量控制、熔断降级和系统负载保护,有效预防服务雪崩。本篇博客深入探讨 Spring Cloud Sentinel 的核心概念,并通过实际案例展示其在项目中的应用。
60 0
|
3月前
|
Java API Nacos
第十二章 Spring Cloud Alibaba Sentinel
第十二章 Spring Cloud Alibaba Sentinel
125 0