# 从浅入深 学习 SpringCloud 微服务架构(八)Sentinel(2)

news2024/6/17 16:07:47

从浅入深 学习 SpringCloud 微服务架构(八)Sentinel(2)

一、sentinel:通用资源保护

1、Rest 实现熔断

Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,
在构造 RestTemplate bean 的时候需要加上 @sentinelRestTemplate 注解。

2、修改 order_service_rest 子工程(子模块)的 Controller 方法,添加降级方法:

/**
 *   spring_cloud_sentinel_demo\order_service_rest\src\main\java\djh\it\order\controller\OrderController.java
 *
 *  2024-5-5 订单的 controller 类 OrderController.java
 */
package djh.it.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import djh.it.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired  //注入 restTemplate 对象
    private RestTemplate restTemplate;

    @SentinelResource(blockHandler = "orderBlockHandler", fallback = "orderFallback")
    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        if(id != 1){
            throw new RuntimeException("错误");
        }
        Product product = null;
        product = restTemplate.getForObject("http://service-product/product/1", Product.class);
        return product;
    }

    /**
     *  定义降级逻辑:sentinel 不同于 hystrix
     *      需要分别定义 熔断执行的降级方法和抛出异常执行的降级方法。
     */
    public Product orderBlockHandler(Long id){
        Product product = new Product();
        product.setProductName("触发熔断--的降级方法");
        return product;
    }
    public Product orderFallback(Long id){
        Product product = new Product();
        product.setProductName("抛出异常执行--的降级方法");
        return product;
    }
}

3、重新运行 order_service_rest 子工程(子模块)的启动类,进行测试:

浏览器地址栏输入:localhost:8086 登录 Sevtinel 控制台,进行设置

注意:需要 浏览器地址栏输入:localhost:9003/order/buy/1 访问请求, Sevtinel 控制台才会有服务名
(因为 Sentinel 默认是懒加载)

1)点击右侧 【service-order-rest】 服务名,再点击【簇点链路】,

会显示出 请求的方法名,

2)点击方法名(如:djh.it.order.controller.OrderController:findById(java.lang.Long))后面的【降级】

新增【降级】规则

降级策略:如:勾选【异常数】

异常数:如:(1) 时间窗口:如:(5)

点击【新增】。

3)浏览器地址栏输入正确请求:localhost:9003/order/buy/1
错误请求:localhost:9003/order/buy/2 多刷新几次,测试熔断方法执行情况。

在这里插入图片描述
在这里插入图片描述
4)等待 5 秒,输入正确请求访问又正常了 localhost:9003/order/buy/1
在这里插入图片描述

二、sentinel:加载本地配置

1、@SentinelResource 注解,可以用 value 属性,指定资源名称。

2、修改 order_service_rest 子工程(子模块)的 Controller 方法,添加 @SentinelResource 注解的 value 属性,指定资源名称。

/**
 *   spring_cloud_sentinel_demo\order_service_rest\src\main\java\djh\it\order\controller\OrderController.java
 *
 *  2024-5-5 订单的 controller 类 OrderController.java
 */
package djh.it.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import djh.it.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired  //注入 restTemplate 对象
    private RestTemplate restTemplate;

    /**
     * @SentinelResource 注解属性
     *      blockHandler : 声明熔断时调用的降级方法。
     *      fallback : 抛出异常执行的降级方法。
     *      value : 自定义的资源名称,如果不设置,默认为当前全类名.方法名。
     */
    @SentinelResource(value = "orderFindByid", blockHandler = "orderBlockHandler", fallback = "orderFallback")
    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        if(id != 1){
            throw new RuntimeException("错误");
        }
        Product product = null;
        product = restTemplate.getForObject("http://service-product/product/1", Product.class);
        return product;
    }

    /**
     *  定义降级逻辑:sentinel 不同于 hystrix
     *      需要分别定义 熔断执行的降级方法和抛出异常执行的降级方法。
     */
    public Product orderBlockHandler(Long id){
        Product product = new Product();
        product.setProductName("触发熔断--的降级方法");
        return product;
    }
    public Product orderFallback(Long id){
        Product product = new Product();
        product.setProductName("抛出异常执行--的降级方法");
        return product;
    }
}

在这里插入图片描述

3、一条限流规则主要由下面几个因素组成:

resource: 资源名,即限流规则的作用对象
count: 限流阈值
grade: 限流阈值类型( QPs或并发线程数 )
limitapp: 流控针对的调用来源,若为 default 则不区分调用来源。
strategy: 调用关系限流策略
controlBehavior: 流量控制效果( 直接拒绝、warm up、匀速排队 )。

4、可以在项目的 application.yml 配置文件中,添加如下配置,来读取本地配置资源文件。

#通过文件读取限流规则
spring.cloud.sentinel.datasource.dsl.file.file=classpath:flowrule.json
spring.cloud.sentinel.datasource.dsl.file.data-type=json
spring.cloud.sentinel.datasource.dsl.file.rule-type=flow

5、修改 order_service_rest 子工程(子模块)的 application.yml 配置,添加读取本地资源配置文件的配置。

##  spring_cloud_sentinel_demo\order_service_rest\src\main\resources\application.yml

server:
  port: 9003  # 启动端口 命令行注入。
#  port: ${port:9003}  # 启动端口设置为动态传参,如果未传参数,默认端口为 9003

spring:
  application:
    name: service-order_rest  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    # MySQL8.0 可以写成  root, 012311 或  'root', '012311'   # MySQL5.7 只能写成 'root', '012311'  # 注意用户名和密码后一定不能有空格。
    username: 'root'
    password: '12311'
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
  cloud:   # 配置 sentinel 服务熔断
    sentinel:
      transport:
        dashboard: localhost:8086  # sentienl 控制台的请求地址。
      datasource:
        ds1:
          file:
            file: classpath:flowrule.json
            data-type: json
            rule-type: flow

eureka:  # 配置 Eureka
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/  # 多个 eurekaserver 用 , 隔开。
  instance:
    prefer-ip-address: true  # 使用 ip 地址注册
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

在这里插入图片描述

6、在 order_service_rest 子工程(子模块)的 Resource 资源根目录下,创建 加载本地 Sentinel 设置的文件 flowrule.json 。

[
	{
		"resource": "orderFindById",
		"controlBehavior": 0,
		"count": 1,
		"grade": 1,
		"limitApp": "default",
		"strategy": 0
	}
]

在这里插入图片描述

7、重新运行 order_service_rest 子工程(子模块)的启动类,进行测试:

1)浏览器地址栏输入:localhost:8086 登录 Sevtinel 控制台

2)览器地址栏输入:localhost:9003/order/buy/1 访问请求, Sevtinel 控制台

3)localhost:8086 登录 Sevtinel 控制台

点击右侧 【service-order-rest】 服务名,再点击【簇点链路】,会发现已经加载到配置的资源名称了。

在这里插入图片描述

三、sentinel:对 resttemplate 的支持

1、修改 order_service_rest 子工程(子模块)的 Controller 方法,注销掉服务降级的方法。

/**
 *   spring_cloud_sentinel_demo\order_service_rest\src\main\java\djh\it\order\controller\OrderController.java
 *
 *  2024-5-5 订单的 controller 类 OrderController.java
 */
package djh.it.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import djh.it.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired  //注入 restTemplate 对象
    private RestTemplate restTemplate;

    /**
     *  @SentinelResource 注解属性
     *      blockHandler : 声明熔断时调用的降级方法。
     *      fallback : 抛出异常执行的降级方法。
     *      value : 自定义的资源名称,如果不设置,默认为当前全类名.方法名。
     *
     *   启动类,添加 @SentinelRestTemplate 注解时(sentinel:对 resttemplate 的支持):
     *      就不需要添加 @SentinelResource 注解和降级方法了。
     */
//    @SentinelResource(value = "orderFindByid", blockHandler = "orderBlockHandler", fallback = "orderFallback")
    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        if(id != 1){
            throw new RuntimeException("错误");
        }
        Product product = null;
        product = restTemplate.getForObject("http://service-product/product/1", Product.class);
        return product;
    }

//    /**
//     *  定义降级逻辑:sentinel 不同于 hystrix
//     *      需要分别定义 熔断执行的降级方法和抛出异常执行的降级方法。
//     */
//    public Product orderBlockHandler(Long id){
//        Product product = new Product();
//        product.setProductName("触发熔断--的降级方法");
//        return product;
//    }
//    public Product orderFallback(Long id){
//        Product product = new Product();
//        product.setProductName("抛出异常执行--的降级方法");
//        return product;
//    }
}

在这里插入图片描述

2、修改 order_service_rest 子工程(子模块)的 启动类,添加 @SentinelRestTemplate 注解。

/**
 *    spring_cloud_sentinel_demo\order_service_rest\src\main\java\djh\it\order\OrderApplication.java
 *
 *   2024-5-5  启动类 OrderApplication.java
 */
package djh.it.order;

import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
//import org.apache.tomcat.util.ExceptionUtils;
import djh.it.order.exception.ExceptionUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
//import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EntityScan("djh.it.order.domain")
@EnableEurekaClient  //激活 EurekaClient,同 @EnableDiscoveryClient 注解相同。
//@EnableFeignClients  //激活 Feign
@EnableCircuitBreaker  // 2)激活 hystrix,  Hystrix 组件 对 RestTemplate 的支持4步:
@EnableHystrixDashboard  // 激活 Hystrix 基于图形化的 DashBoard(仪表板)监控平台
public class OrderApplication {
    /**
     *  启动类,添加 @SentinelRestTemplate 注解时(sentinel:对 resttemplate 的支持):
     *      Controller 类 就不需要添加 @SentinelResource 注解和降级方法了。
     *
     *   资源名:
     *      httpmethod:schema://host:port/path : 协议、主机、端口和路径。
     *      httpmethod:schema://host:port : 协议、主机和端口。
     *
     *   @SentinelRestTemplate 注解:
     *      异常降级:
     *          fallback      : 降级方法
     *          fallbackClass : 降级配置类。
     *      限流熔断:
     *          blockHandler
     *          blockHandlerClass
     */

    @LoadBalanced
    @Bean
    @SentinelRestTemplate(fallbackClass = ExceptionUtils.class, fallback = "handlerFallback",
            blockHandler = "handleBlock", blockHandlerClass = ExceptionUtils.class)
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}

在这里插入图片描述

3、在 order_service_rest 子工程(子模块)创建 定义一个类和静态方法 ExceptionUtils.java

/**
 *  spring_cloud_sentinel_demo\order_service_rest\src\main\java\djh\it\order\exception\ExceptionUtils.java
 *
 *   定义一个类和静态方法 ExceptionUtils.java
 */

package djh.it.order.exception;

import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import djh.it.order.domain.Product;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;

public class ExceptionUtils {
    /**
     *  静态方法
     *      返回值: SentinelClientHttpResponse
     *      参数: request,byte[],clientRquestExcetion,blockException
     */

    //限流熔断业务逻辑
    public static SentinelClientHttpResponse handleBlock ( HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex){
//        System.err.println("0ops: " + ex.getClass().getCanonicalName());
//        return new SentinelClientHttpResponse( "限流熔断降级");

        Product product = new Product();
        product.setProductName("block");
        return new SentinelClientHttpResponse(JSON.toJSONString(product));
    }

    //异常降级业务逻辑
    public static SentinelClientHttpResponse handlerFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex){
//        System.err.println("fallback: " + ex.getClass().getCanonicalName());
//        return new SentinelClientHttpResponse( "异常熔断降级");

        Product product = new Product();
        product.setProductName("Fallback");
        return new SentinelClientHttpResponse(JSON.toJSONString(product));
    }

}


4、修改 order_service_rest 子工程(子模块)的 application.yml 文件,添加 sentinel 立即加载。

##  spring_cloud_sentinel_demo\order_service_rest\src\main\resources\application.yml

server:
  port: 9003  # 启动端口 命令行注入。
#  port: ${port:9003}  # 启动端口设置为动态传参,如果未传参数,默认端口为 9003

spring:
  application:
    name: service-order_rest  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    # MySQL8.0 可以写成  root, 012311 或  'root', '012311'   # MySQL5.7 只能写成 'root', '012311'  # 注意用户名和密码后一定不能有空格。
    username: 'root'
    password: '12311'
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
  cloud:   # 配置 sentinel 服务熔断
    sentinel:
      transport:
        dashboard: localhost:8086  # sentienl 控制台的请求地址。
      datasource:
        ds1:
          file:
            file: classpath:flowrule.json
            data-type: json
            rule-type: flow
      eager: true  # 立即加载

eureka:  # 配置 Eureka
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/  # 多个 eurekaserver 用 , 隔开。
  instance:
    prefer-ip-address: true  # 使用 ip 地址注册
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

# 配置 feign 日志的输出。
# 日志配置:NONE:GI 不输出日志,BASIC:适用于生产环境追踪问题,HEADERS:在BASIC基础上,记录请求和响应头信息,FULL:记录所有。
logging:
  level:
    djh.it.order.feign.ProductFeignClient: debug

#feign:
#  client:
#    config:
#      default:
#        connectTimeout: 5000   #服务之间建立连接所用的时间  #不设置 connectTimeout 会导致 readTimeout 设置不生效
#        readTimeout: 5000   #建立连接后从服务端读取到数据用的时间
#      service-product:  # 需要调用的服务名称
#        loggerLevel: FULL
#  hystrix:  # 开启对 hystrix 的支持。
#    enabled: true

#hystrix:  # 配置 hystrix 熔断(Hystrix:基于 RestTemplate 的统一降级配置)
#  command:
#    default:
#      execution:
#        isolation:
#          thread:
#            timeoutInMilliseconds: 5000  # 默认的熔断超时时间为1 秒,若1秒没有返回数据,会自动触发降级逻辑。
#      circuitBreaker:
#        requestVolumeThreshold: 5  # 触发熔断的最小请求次数,默认 20 次/秒。
#        sleepWindbwInMilliseconds: 10000  # 熔断多少秒后去尝试请求。默认打开状态的时间是 5秒
#        errorThresholdPercentage: 50  # 触发熔断的失败请求最小占比,默认 50%
#management:   # 配置 Actuator 获取 hystrix 的监控数据 暴躁端点。
#  endpoints:
#    web:
#      exposure:
#        include: '*'   # 暴露所有端点。

在这里插入图片描述

5、重新运行 order_service_rest 子工程(子模块)的启动类,进行测试:

1)浏览器地址栏输入:localhost:8086 登录 Sevtinel 控制台

2)览器地址栏输入:localhost:9003/order/buy/1 访问请求, Sevtinel 控制台

3)localhost:8086 登录 Sevtinel 控制台

点击右侧 【service-order-rest】 服务名,再点击【簇点链路】,会发现已经加载到配置的资源名称了。

4)设置【流量控制】

如:点击一个资源名称( GET:http://service-product/product/1 )

点击后面的【+流控】

阀值类型:勾选 (QPS)

单机阀值:(1)

点击 【新增】。

在这里插入图片描述

5)配置好【流量控制】后,再次刷新请求页面 localhost:9003/order/buy/1

发现点击刷新页面慢时,正常显示,点击快时,就会触发熔断保护方法。

在这里插入图片描述

在这里插入图片描述

四、sentinel:对 feign 的支持

1、修改 order_service_feign 子工程(子模块)的 pom.xml 文件,添加 sentinel 依赖坐标。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring_cloud_sentinel_demo</artifactId>
        <groupId>djh.it</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order_service_feign</artifactId>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--            <version>5.1.32</version>-->
            <version>8.0.26</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- 导入 eureka 注册中心 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- springcloud 整合 openFeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- Hystrix 组件 对 RestTemplate 的支持4步:1)引入 Hystrix 依赖坐标 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!-- 引入 hystrix 的监控信息 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
        <!-- 引入 sentinel 熔断 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<!--            <version>2.0.0.RELEASES</version>-->
        </dependency>
    </dependencies>
</project>
<!--  idea2019\spring_cloud_sentinel_demo\order_service_feign\pom.xml -->

在这里插入图片描述

2、修改 order_service_feign 子工程(子模块)的 application.yml 文件,添加 开启 sentinel 支持。

##  spring_cloud_sentinel_demo\order_service_feign\src\main\resources\application.yml

server:
  port: 9002  # 启动端口 命令行注入。
#  port: ${port:9002}  # 启动端口设置为动态传参,如果未传参数,默认端口为 9002

spring:
  application:
    name: service-order_feign  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    # MySQL8.0 可以写成  root, 012311 或  'root', '012311'   # MySQL5.7 只能写成 'root', '012311'  # 注意用户名和密码后一定不能有空格。
    username: 'root'
    password: '12311'
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
  cloud:   # 配置 sentinel 服务熔断
    sentinel:
      transport:
        dashboard: localhost:8086  # sentienl 控制台的请求地址。

feign:   # 激活 sentinel 的支持
  sentinel:
    enabled: true

eureka:  # 配置 Eureka
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/  # 多个 eurekaserver 用 , 隔开。
  instance:
    prefer-ip-address: true  # 使用 ip 地址注册
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

在这里插入图片描述

3、修改 order_service_feign 子工程(子模块)的 接口类,配置 FeignClient。

/**
 *   spring_cloud_sentinel_demo\order_service_feign\src\main\java\djh\it\order\feign\ProductFeignClient.java
 *
 *   2024-5-5  创建 调用 feign 组件的接口类 ProductFeignClient.java
 *   声明需要调用的微服务名称 @FeignClient, name: 服务提供者的名称, fallback:配置熔断发生的降级方法。
 */

package djh.it.order.feign;

import djh.it.order.domain.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name="service-product", fallback = ProductFeignClientCallBack.class)  //调用 FeignClient 并添加降级方法的支持
public interface ProductFeignClient {
    //配置需要调用的微服务接口
    @RequestMapping(value = "/product/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable("id") Long id);
}

4、在 order_service_feign 子工程(子模块)创建 接口的 实现类,配置熔断方法。

/**
 *   spring_cloud_sentinel_demo\order_service_feign\src\main\java\djh\it\order\feign\ProductFeignClientCallBack.java
 *
 *   2024-5-5  创建 feign 组件的接口类 ProductFeignClient 的实现类 ProductFeignClientCallBack.java
 *   配置熔断触发的降级逻辑。
 */

package djh.it.order.feign;

import djh.it.order.domain.Product;
import org.springframework.stereotype.Component;

@Component
public class ProductFeignClientCallBack implements ProductFeignClient{
    // 熔断降级的方法
    public Product findById(Long id) {
        Product product = new Product();
        product.setProductName("hystrix:基于 feign 调用的熔断配置 -- feign 调用触发熔断降级的方法。");
        return product;
    }
}

5、order_service_feign 子工程(子模块)的 商品 类。

/**
 *   spring_cloud_sentinel_demo\order_service_feign\src\main\java\djh\it\order\domain\Product.java
 *
 *  2024-5-5  商品实体类 Product.java
 */
package djh.it.order.domain;

import lombok.Data;
import java.math.BigDecimal;

@Data
public class Product {

    private Long id;
    private String productName;
    private Integer status;
    private BigDecimal price;
    private String productDesc;
    private String caption;
    private Integer inventory;
}

6、order_service_feign 子工程(子模块)的 Controller 类。

/**
 *   spring_cloud_sentinel_demo\order_service_feign\src\main\java\djh\it\order\controller\OrderFeignController.java
 *
 *  2024-5-5 订单的 controller 类 OrderFeignController.java
 */
package djh.it.order.controller;

import djh.it.order.domain.Product;
import djh.it.order.feign.ProductFeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
@RequestMapping("/order")
public class OrderFeignController {

    @Resource    //按类型名称注入 调用 feign 组件的接口类 ProductFeignClient
    //@Autowired   //自动注入 调用 feign 组件的接口类 ProductFeignClient //有时变量名报红,可替换为 @Resource 注解
    private ProductFeignClient productFeignClient;

    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        Product product = null;
       //调用 feign 组件的接口类 的方法
        product = productFeignClient.findById(id);
        return product;
    }
}

7、order_service_feign 子工程(子模块)的 启动 类。

/**
 *    spring_cloud_sentinel_demo\order_service_feign\src\main\java\djh\it\order\OrderFeignApplication.java
 *
 *   2024-5-5  启动类 OrderFeignApplication.java
 */
package djh.it.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EntityScan("djh.it.order.domain")
@EnableEurekaClient  //激活 EurekaClient,同 @EnableDiscoveryClient 注解相同。
@EnableFeignClients  //激活 Feign
public class OrderFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignApplication.class, args);
    }
}

8、重新运行 order_service_feign 子工程(子模块)的启动类,进行测试:

1)浏览器地址栏输入:localhost:8086 登录 Sevtinel 控制台

2)览器地址栏输入:localhost:9002/order/buy/1 访问请求, Sevtinel 控制台

3)localhost:8086 登录 Sevtinel 控制台

点击右侧 【service-order-feign】 服务名,再点击【簇点链路】,会发现已经加载到配置的资源名称了。

4)设置【流量控制】

如:点击一个资源名称( GET:http://service-product/product/1 )

点击后面的【+流控】

阀值类型:勾选 (QPS)

单机阀值:(1)

点击 【新增】。

5)配置好【流量控制】后,再次刷新请求页面 localhost:9002/order/buy/1

发现点击刷新页面慢时,正常显示,点击快时,就会触发熔断保护方法。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

上一节链接请点击 :

# 从浅入深 学习 SpringCloud 微服务架构(八)Sentinel(1)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1655723.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Lazada商品详情API接口:深度解析与应用

前言 在当今电子商务的繁荣时代&#xff0c;对于电商平台来说&#xff0c;提供一套高效、稳定的API接口是非常重要的。Lazada&#xff0c;作为东南亚领先的电商平台之一&#xff0c;其API接口体系为卖家、开发者以及第三方服务提供了丰富的功能和数据支持。其中&#xff0c;商品…

多线程学习Day09

10.Tomcat线程池 LimitLatch 用来限流&#xff0c;可以控制最大连接个数&#xff0c;类似 J.U.C 中的 Semaphore 后面再讲 Acceptor 只负责【接收新的 socket 连接】 Poller 只负责监听 socket channel 是否有【可读的 I/O 事件】 一旦可读&#xff0c;封装一个任务对象&#x…

保姆级零基础微调大模型(LLaMa-Factory,多卡版)

此处非常感谢https://github.com/hiyouga/LLaMA-Factory这个项目。 看到网上的教程很多都是教如何用webui来微调的,这里出一期命令行多卡微调教程~ 1. 模型准备 模型下载比较方便的方法: 1. modelscope社区(首选,速度很高,并且很多需要申请的模型都有)注意要选择代码…

Redis快速学习

Redis快速学习 一、 Redis快速入门1.1 初始Redis1.1.1 Redis的存储方式1.1.2 NoSQL 与 sql 之间的区别 1.2 Redis概述1.2.1 Redis是什么1.2.2 Redis有什么用1.2.3 Redis的特性 1.3 Redis安装测试1.3.1 Redis Linux安装 1.4 Redis测试工具1.5 Redis的基本知识 二、Redis的五大数…

【Elasticsearch运维系列】Elasticsearch7.12.1启动指定版本JDK:你学废了吗?

一、背景 一套生ES集群&#xff0c;版本为7.12.1&#xff0c;近期频繁告警&#xff0c;频繁出现索引分片异常&#xff0c;索引状态异常&#xff0c;导致应用无法正常写入ES&#xff0c;另外&#xff0c;也经常出现节点掉问题。通过分析相关ES日志&#xff0c;显示和当前JAVA G…

C++ | Leetcode C++题解之第77题组合

题目&#xff1a; 题解&#xff1a; class Solution { public:vector<int> temp;vector<vector<int>> ans;vector<vector<int>> combine(int n, int k) {// 初始化// 将 temp 中 [0, k - 1] 每个位置 i 设置为 i 1&#xff0c;即 [0, k - 1] 存…

细说夜莺监控系统告警自愈机制

虽说监控系统最侧重的功能是指标采集、存储、分析、告警&#xff0c;为了能够快速恢复故障&#xff0c;告警自愈机制也是需要重点投入建设的&#xff0c;所有可以固化为脚本的应急预案都可以使用告警自愈机制来快速驱动。夜莺开源项目从 v7 版本开始内置了告警自愈模块&#xf…

2024/5/9 英语每日一段

With runoff from this year’s snow and rain boosting the levels of California’s reservoirs, state water managers on Tuesday announced plans to increase deliveries of supplies from the State Water Project to 40% of full allotments, up from 30% last month. …

如何用opencv去掉单元格的边框线,以提高Tesseract识别率?

在OpenCV中处理从表格切割下来的图片&#xff0c;并去掉单元格的边框线&#xff0c;以提升Tesseract的识别准确率&#xff0c;确实是一个具有挑战性的任务。在这种情况下&#xff0c;我们需要采取一种策略来预处理图像&#xff0c;使得数字与背景之间的对比度增强&#xff0c;同…

聚观早报 | 苹果新款iPad Pro发布;国产特斯拉4月交付量

聚观早报每日整理最值得关注的行业重点事件&#xff0c;帮助大家及时了解最新行业动态&#xff0c;每日读报&#xff0c;就读聚观365资讯简报。 整理丨Cutie 5月9日消息 苹果新款iPad Pro发布 国产特斯拉4月交付量 iOS 18新功能爆料 真我GT Neo6续航细节 三星Galaxy Z F…

楼宇自控远程I/O革新BACnet/IP模块在暖通空调系统

在现代智能建筑的浪潮中&#xff0c;BACnet/IP分布式远程I/O控制器正逐步成为暖通空调&#xff08;HAVC&#xff09;系统升级转型的得力助手。本文将以某大型商业综合体为例&#xff0c;揭示BACnet/IP I/O模块如何在复杂多变的环境中发挥其独特优势&#xff0c;实现HVAC系统的智…

Flink 算子

Flink 算子 用户通过算子能将一个或多个 DataStream 转换成新的 DataStream&#xff0c;在应用程序中可以将多个数据转换算子合并成一个复杂的数据流拓扑。 这部分内容将描述 Flink DataStream API 中基本的数据转换 API&#xff0c;数据转换后各种数据分区方式&#xff0c;以…

企业网盘竟还能这样用,可道云teamOS:三大冷门使用技巧分享

在日常工作中&#xff0c;大家是否有为海量的文件的管理感到头疼&#xff1f; 每当急需某个重要文件时&#xff0c;总是在各种文件夹中寻寻觅觅半天。这种困扰&#xff0c;我相信许多人都有过。 在这种时候&#xff0c;专业的文件管理软件能帮助我们解决大部分的麻烦。 今天我…

【数据库原理及应用】期末复习汇总高校期末真题试卷09

试卷 一、填空题(每空1分&#xff0c;共10分) 数据的完整性是指数据的________、有效性和相容性。数据模型通常由________、数据操作以及数据约束条件等三要素组成。在关系的有关术语中&#xff0c;关系表中的每一行称作________&#xff0c;每一列称作属性。信息的三种世界是…

WPS二次开发系列:一文快速了解WPS SDK功能场景

作者持续关注 WPS二次开发专题系列&#xff0c;持续为大家带来更多有价值的WPS开发技术细节&#xff0c;如果能够帮助到您&#xff0c;请帮忙来个一键三连&#xff0c;更多问题请联系我&#xff08;QQ:250325397&#xff09; 目录 SDK功能介绍 功能详解&#xff1a; 打开文档…

yaml配置文件的在深度学习中的简单应用

1 .创作灵感 小伙伴们再阅读深度学习模型的代码的时候&#xff0c;经常会遇到yaml格式的配置文件。用这个配置文件是因为我们在训练模型的时候会涉及很多的参数&#xff0c;如果这些参数东一个&#xff0c;西一个&#xff0c;我们调起来的时候就会很不方便&#xff0c;所以用y…

社交媒体数据恢复:飞月

首先&#xff0c;请注意&#xff0c;任何数据恢复操作都不能保证100%找回丢失的数据。因此&#xff0c;在进行数据恢复前&#xff0c;请做好备份&#xff0c;并谨慎操作。 以下是一般性的数据恢复步骤&#xff1a; 导出聊天记录&#xff1a;首先尝试导出飞月的聊天记录。这可以…

全网最全:一文入门最热的LLM应用开发框架LangChain

f#### 1. LangChain 简介 1.1. LangChain 发展史 LangChain 的作者是 Harrison Chase&#xff0c;最初是于 2022 年 10 月开源的一个项目&#xff0c;在 GitHub 上获得大量关注之后迅速转变为一家初创公司。2017 年 Harrison Chase 还在哈佛上大学&#xff0c;如今已是硅谷的…

Promise.all和 race

Promise.all() all方法可以完成并行任务&#xff0c; 它接收一个数组&#xff0c;数组的每一项都是一个promise对象。返回值&#xff1a; 成功时&#xff1a;当数组中所有的promise的状态都达到resolved的时候&#xff0c;就返回包含所有 Promise 结果的数组&#xff0c;并且…

短视频矩阵系统贴牌---saas源头开发

一、短视频矩阵运营注意事项&#xff1a; 如&#xff1a;房产行业 短视频矩阵运营是一个系统化的项目&#xff0c;涉及多个平台和账号的管理&#xff0c;以及内容的创作、发布和优化等多个方面。 以下是短视频矩阵运营的注意事项文档的概要以及结果运营数据 一周持续运营量 二…