• Spring cloud alibaba实战


    这里不做过多理论说明,直接进入实战操作。

    第一章:Nacos Discovery——服务发现与注册管理

    • Nacos Server启动。
      • 源码下载,下载地址https://gitee.com/mirrors/Nacos/repository/archive/2.1.0
      • 解压进入文件根目录,编辑pom.xml,配置本地及alibaba的maven仓库地址保存。(file://xxx/Repository改为自己本地仓库位置)
        1. <repositories>
        2. <repository>
        3. <id>Localhostid>
        4. <name>Localhostname>
        5. <url>file://xxx/Repositoryurl>
        6. repository>
        7. <repository>
        8. <id>alimavenid>
        9. <name>aliyun mavenname>
        10. <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
        11. <releases>
        12. <enabled>trueenabled>
        13. releases>
        14. <snapshots>
        15. <enabled>falseenabled>
        16. snapshots>
        17. repository>
        18. repositories>
        19. <pluginRepositories>
        20. <pluginRepository>
        21. <id>alimavenid>
        22. <name>aliyun mavenname>
        23. <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
        24. <releases>
        25. <enabled>trueenabled>
        26. releases>
        27. <snapshots>
        28. <enabled>falseenabled>
        29. snapshots>
        30. pluginRepository>
        31. <pluginRepository>
        32. <id>Localhostid>
        33. <name>Localhostname>
        34. <url>file://xxx/Repositoryurl>
        35. pluginRepository>
        36. pluginRepositories>

      • 进入cmd,执行mvn -Dmaven.test.skip=true clean package命令进行编译。
      • 编译完成,进入\distribution\target\nacos-server-2.1.0\nacos\bin,打开cmd,执行startup.cmd -m standalone命令单机启动nacos server。
      • 启动之后,打开浏览器访问http://127.0.0.1:8848访问控制台,输入账号密码nacos登录进如控制台。
      • Nacos server启动完成。
    • 创建父工程alibaba-spring-cloud。
      • 创建maven工程,只保留pom.xml用作添加公共依赖。
      • 添加公共依赖,仓库路径,以及版本定位。
        1. <properties>
        2. <spring-cloud.version>2021.0.1spring-cloud.version>
        3. <spring-cloud-alibaba.version>2021.0.1.0spring-cloud-alibaba.version>
        4. properties>
        5. <parent>
        6. <groupId>org.springframework.cloudgroupId>
        7. <artifactId>spring-cloud-buildartifactId>
        8. <version>3.1.1version>
        9. <relativePath/>
        10. parent>
        11. <dependencies>
        12. <dependency>
        13. <groupId>org.projectlombokgroupId>
        14. <artifactId>lombokartifactId>
        15. dependency>
        16. <dependency>
        17. <groupId>org.springframework.cloudgroupId>
        18. <artifactId>spring-cloud-starter-bootstrapartifactId>
        19. dependency>
        20. dependencies>
        21. <dependencyManagement>
        22. <dependencies>
        23. <dependency>
        24. <groupId>org.springframework.bootgroupId>
        25. <artifactId>spring-boot-dependenciesartifactId>
        26. <version>${spring-boot.version}version>
        27. <type>pomtype>
        28. <scope>importscope>
        29. dependency>
        30. <dependency>
        31. <groupId>org.springframework.cloudgroupId>
        32. <artifactId>spring-cloud-dependenciesartifactId>
        33. <version>${spring-cloud.version}version>
        34. <type>pomtype>
        35. <scope>importscope>
        36. dependency>
        37. <dependency>
        38. <groupId>com.alibaba.cloudgroupId>
        39. <artifactId>spring-cloud-alibaba-dependenciesartifactId>
        40. <version>${spring-cloud-alibaba.version}version>
        41. <type>pomtype>
        42. <scope>importscope>
        43. dependency>
        44. dependencies>
        45. dependencyManagement>
        46. <pluginRepositories>
        47. <pluginRepository>
        48. <id>aliyun-pluginid>
        49. <url>https://maven.aliyun.com/repository/publicurl>
        50. <releases>
        51. <enabled>trueenabled>
        52. releases>
        53. <snapshots>
        54. <enabled>falseenabled>
        55. snapshots>
        56. pluginRepository>
        57. pluginRepositories>
        58. <repositories>
        59. <repository>
        60. <id>aliyunid>
        61. <name>aliyunname>
        62. <url>http://maven.aliyun.com/nexus/content/groups/publicurl>
        63. repository>
        64. repositories>
        65. 3. Nacos client provider创建。
        66. a) 创建alibaba-spring-cloud-provider子工程,添加依赖。
        67. <parent>
        68. <groupId>com.cloudgroupId>
        69. <artifactId>alibaba-spring-cloudartifactId>
        70. <version>1.0-SNAPSHOTversion>
        71. <relativePath>../pom.xmlrelativePath>
        72. parent>
        73. <properties>
        74. <java.version>1.8java.version>
        75. properties>
        76. <dependencies>
        77. <dependency>
        78. <groupId>com.alibaba.cloudgroupId>
        79. <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        80. dependency>
        81. <dependency>
        82. <groupId>org.springframework.bootgroupId>
        83. <artifactId>spring-boot-starter-webartifactId>
        84. dependency>
        85. <dependency>
        86. <groupId>org.springframework.bootgroupId>
        87. <artifactId>spring-boot-starter-actuatorartifactId>
        88. dependency>
        89. dependencies>

      • 启动类添加@EnableDiscoveryClient注解。
      • application.yml配置文件添加配置,定义服务名称,配置nacos连接地址及账号密码。
        1. server:
        2. port: 18080
        3. spring:
        4. application:
        5. name: provider-service
        6. cloud:
        7. nacos:
        8. discovery:
        9. server-addr: 127.0.0.1:8848
        10. enabled: true
        11. username: nacos
        12. password: nacos
        13. management:
        14. endpoints:
        15. web:
        16. exposure:
        17. include: "*"
        18. endpoint:
        19. health:
        20. show-details: always

      • 创建Controller并添加接口。
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
        3. import org.springframework.http.HttpStatus;
        4. import org.springframework.http.ResponseEntity;
        5. import org.springframework.web.bind.annotation.*;
        6. import javax.annotation.Resource;
        7. import java.util.Map;
        8. /**
        9. * 项目名称: provider
        10. * 包名称: com.cloud.controller
        11. * 类名称: ProviderController
        12. * 类描述:
        13. * 创建人: zhihong.zhu
        14. * 创建时间: 2022/8/9 14:45
        15. * 修改人:
        16. * 修改时间:
        17. * 修改备注:
        18. */
        19. @RestController
        20. public class ProviderController {
        21. @GetMapping("/echo/{string}")
        22. public String echo(@PathVariable String string) {
        23. return "hello Nacos Discovery " + string;
        24. }
        25. }

      • 启动之后,登录nacos查看服务列表已存在该服务。
    • Nacos client consumer创建。
      • 创建alibaba-spring-cloud-consumer子工程,添加依赖。
        1. <parent>
        2. <groupId>com.cloudgroupId>
        3. <artifactId>alibaba-spring-cloudartifactId>
        4. <version>1.0-SNAPSHOTversion>
        5. <relativePath>../pom.xmlrelativePath>
        6. parent>
        7. <properties>
        8. <java.version>1.8java.version>
        9. properties>
        10. <dependencies>
        11. <dependency>
        12. <groupId>org.springframework.bootgroupId>
        13. <artifactId>spring-boot-starter-webartifactId>
        14. dependency>
        15. <dependency>
        16. <groupId>com.alibaba.cloudgroupId>
        17. <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        18. dependency>
        19. <dependency>
        20. <groupId>org.springframework.bootgroupId>
        21. <artifactId>spring-boot-starter-actuatorartifactId>
        22. dependency>
        23. <dependency>
        24. <groupId>org.springframework.cloudgroupId>
        25. <artifactId>spring-cloud-starter-loadbalancerartifactId>
        26. dependency>
        27. dependencies>

      • 启动类添加@EnableDiscoveryClient注解。
      • application.yml配置文件添加配置,定义服务名称,配置nacos连接地址及账号密码。
        1. server:
        2. port: 18011
        3. spring:
        4. application:
        5. name: consumer-service
        6. cloud:
        7. nacos:
        8. discovery:
        9. server-addr: 127.0.0.1:8848
        10. enabled: true
        11. username: nacos
        12. password: nacos
        13. loadbalancer.nacos.enabled: true
        14. management:
        15. endpoints:
        16. web:
        17. exposure:
        18. include: "*"
        19. endpoint:
        20. health:
        21. show-details: always

      • 创建Controller并添加接口。
        1. package com.cloud.controller;
        2. import com.cloud.service.EchoService;
        3. import org.springframework.http.ResponseEntity;
        4. import org.springframework.web.bind.annotation.PathVariable;
        5. import org.springframework.web.bind.annotation.RequestMapping;
        6. import org.springframework.web.bind.annotation.RestController;
        7. import org.springframework.web.client.RestTemplate;
        8. import javax.annotation.Resource;
        9. /**
        10. * 项目名称: consumer
        11. * 包名称: com.cloud.controller
        12. * 类名称: ConsumerController
        13. * 类描述:
        14. * 创建人: zhihong.zhu
        15. * 创建时间: 2022/8/11 9:34
        16. * 修改人:
        17. * 修改时间:
        18. * 修改备注:
        19. */
        20. @RestController
        21. public class ConsumerController {
        22. @Resource
        23. private RestTemplate restTemplate;
        24. @RequestMapping("/echo/{string}")
        25. public String echo(@PathVariable String string) {
        26. return restTemplate.getForObject("http://provider-service/echo/{string}", String.class, string);
        27. }
        28. }

      • 创建RestTemplateConfig配置类,同时添加负载均衡支持注解。
        1. package com.cloud.configurer;
        2. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
        3. import org.springframework.context.annotation.Bean;
        4. import org.springframework.context.annotation.Configuration;
        5. import org.springframework.web.client.RestTemplate;
        6. /**
        7. * 项目名称: consumer
        8. * 包名称: com.cloud.configurer
        9. * 类名称: RestTemplateConfig
        10. * 类描述: RestTemplate配置
        11. * 创建人: zhihong.zhu
        12. * 创建时间: 2022/8/11 9:32
        13. * 修改人:
        14. * 修改时间:
        15. * 修改备注:
        16. */
        17. @Configuration
        18. public class RestTemplateConfig {
        19. @Bean
        20. @LoadBalanced
        21. public RestTemplate createRestTemplate(){
        22. return new RestTemplate();
        23. }
        24. }

      • 启动之后,登录nacos查看服务列表已存在该服务。
      • 访问http://localhost:18011/echo/hello-world实现服务调用。

    第二章:Nacos OpenFeign——使用openFeign实现服务调用

    • 还使用alibaba-spring-cloud-consumer子工程,添加依赖。
      1. <dependency>
      2. <groupId>org.springframework.cloudgroupId>
      3. <artifactId>spring-cloud-starter-openfeignartifactId>
      4. dependency>

    • 创建EchoService接口类,添加@FeignClient(name = "provider-service",fallback = EchoServiceFallback.class)注解。name—远程服务名称,fallback—熔断降级处理类。(FeignClient 已经默认集成了 Ribbon)
      1. package com.cloud.service;
      2. import org.springframework.cloud.openfeign.FeignClient;
      3. import org.springframework.web.bind.annotation.GetMapping;
      4. import org.springframework.web.bind.annotation.PathVariable;
      5. import org.springframework.web.bind.annotation.RequestParam;
      6. @FeignClient(name = "provider-service",fallback = EchoServiceFallback.class)
      7. public interface EchoService {
      8. @GetMapping("/echo/{str}")
      9. String echo(@PathVariable("str") String str);
      10. @GetMapping("/notFound")
      11. String notFound();
      12. }
    • 创建EchoServiceFallback类,实现EchoService接口类,实现两个方法,编写降级后处理业务。
      1. package com.cloud.service;
      2. import org.springframework.stereotype.Component;
      3. import org.springframework.web.bind.annotation.PathVariable;
      4. import org.springframework.web.bind.annotation.RequestParam;
      5. /**
      6. * 项目名称: consumer
      7. * 包名称: com.cloud.service
      8. * 类名称: EchoServiceFallback
      9. * 类描述:
      10. * 创建人: zhihong.zhu
      11. * 创建时间: 2022/8/11 9:53
      12. * 修改人:
      13. * 修改时间:
      14. * 修改备注:
      15. */
      16. @Component
      17. public class EchoServiceFallback implements EchoService{
      18. @Override
      19. public String echo(@PathVariable("str") String str) {
      20. return "echo fallback";
      21. }
      22. @Override
      23. public String notFound() {
      24. return "notFound fallback";
      25. }
      26. }

    • 在ConsumerController再添加接口,调用EchoService的两个方法。
      1. package com.cloud.controller;
      2. import com.cloud.service.EchoService;
      3. import org.springframework.http.ResponseEntity;
      4. import org.springframework.web.bind.annotation.PathVariable;
      5. import org.springframework.web.bind.annotation.RequestMapping;
      6. import org.springframework.web.bind.annotation.RestController;
      7. import org.springframework.web.client.RestTemplate;
      8. import javax.annotation.Resource;
      9. /**
      10. * 项目名称: consumer
      11. * 包名称: com.cloud.controller
      12. * 类名称: ConsumerController
      13. * 类描述:
      14. * 创建人: zhihong.zhu
      15. * 创建时间: 2022/8/11 9:34
      16. * 修改人:
      17. * 修改时间:
      18. * 修改备注:
      19. */
      20. @RestController
      21. public class ConsumerController {
      22. @Resource
      23. private RestTemplate restTemplate;
      24. @Resource
      25. private EchoService echoService;
      26. @RequestMapping("/echo/{string}")
      27. public String echo(@PathVariable String string) {
      28. return restTemplate.getForObject("http://provider-service/echo/{string}", String.class, string);
      29. }
      30. @RequestMapping("/echoForFeign/{string}")
      31. public String echoForFeign(@PathVariable String string) {
      32. return echoService.echo(string);
      33. }
      34. @RequestMapping("/notFound")
      35. public String notFound(){
      36. return echoService.notFound();
      37. }
      38. }

    • 启动服务,访问http://localhost:18011/echoForFeign/hello-world实现服务调用,访问http://localhost:18011/notFound返回降级的业务内容。

    第三章:Nacos config——配置管理

    • 与spring cloud config相比,Nacos config不需要单独创建配置中心服务,不需要创建云仓库,不需要MQ传递更新消息。一站式完成动态配置。
    • 创建alibaba-spring-cloud-config子工程,添加依赖。
      1. <parent>
      2. <groupId>com.cloudgroupId>
      3. <artifactId>alibaba-spring-cloudartifactId>
      4. <version>1.0-SNAPSHOTversion>
      5. <relativePath>../pom.xmlrelativePath>
      6. parent>
      7. <properties>
      8. <java.version>1.8java.version>
      9. properties>
      10. <dependencies>
      11. <dependency>
      12. <groupId>org.springframework.bootgroupId>
      13. <artifactId>spring-boot-starter-webartifactId>
      14. dependency>
      15. <dependency>
      16. <groupId>com.alibaba.cloudgroupId>
      17. <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
      18. dependency>
      19. <dependency>
      20. <groupId>org.springframework.cloudgroupId>
      21. <artifactId>spring-cloud-starter-bootstrapartifactId>
      22. dependency>
      23. dependencies>

    • resources下创建bootstrap.yml并添加配置。(项目启动时最先加载bootstrap.yml配置)
      1. server:
      2. port: 18082
      3. spring:
      4. application:
      5. name: nacos-config
      6. cloud:
      7. nacos:
      8. config:
      9. server-addr: 127.0.0.1:8848
      10. file-extension: yml
      11. #优先级shared-configs < extension-configs < ${spring.application.name}-${spring-profiles-active}.${file-extension}
      12. shared-configs:
      13. - data-id: nacos-config-shared1.yml
      14. group: SHARED1_GROUP
      15. refresh: true
      16. - data-id: nacos-config-shared2.yml
      17. group: SHARED1_GROUP
      18. refresh: false
      19. extension-configs:
      20. - data-id: nacos-config-extension1.yml
      21. group: EXTENSION1_GROUP
      22. refresh: true
      23. - data-id: nacos-config-extension2.yml
      24. group: EXTENSION2_GROUP
      25. refresh: false
      26. profiles:
      27. active: dev

    • 配置属性说明:
      • file-extension——配置文件后缀(properties、yml)
      • shared-configs——共享配置,有多个配置可用此属性,格式如上。
      • data-id——资源ID,指定Nacos创建配置文件时的Data ID。此属性值必须加后缀名,file-extension不会自动拼接到此属性值。
      • group——分组,指定Nacos创建配置文件时的Group。默认DEFAULT_GROUP。
      • refresh——是否动态刷新。此属性实现时需与注解配合,后面讲。
      • extension-configs——扩展配置。与shared-configs用途一样,只是优先级不一样。格式如上。
      • 优先级shared-configs < extension-configs < ${spring.application.name}-${spring-profiles-active}.${file-extension}
    • 创建Controller类,并创建接口。添加@RefreshScope注解结合配置文件的refresh配置实现动态刷新。
        1. package com.cloud.controller;
        2. import com.google.common.collect.Maps;
        3. import org.springframework.beans.factory.annotation.Value;
        4. import org.springframework.cloud.context.config.annotation.RefreshScope;
        5. import org.springframework.web.bind.annotation.RequestMapping;
        6. import org.springframework.web.bind.annotation.RestController;
        7. import java.util.HashMap;
        8. import java.util.Map;
        9. /**
        10. * 项目名称: config
        11. * 包名称: com.cloud.controller
        12. * 类名称: ConfigController
        13. * 类描述:
        14. * 创建人: zhihong.zhu
        15. * 创建时间: 2022/8/11 14:31
        16. * 修改人:
        17. * 修改时间:
        18. * 修改备注:
        19. */
        20. @RestController
        21. @RefreshScope
        22. public class ConfigController {
        23. @Value("${user.name}")
        24. private String name;
        25. @Value("${user.age}")
        26. private String age;
        27. @Value("${shared1}")
        28. private String shared1;
        29. @Value("${shared2}")
        30. private String shared2;
        31. @Value("${extension1}")
        32. private String extension1;
        33. @Value("${extension2}")
        34. private String extension2;
        35. @RequestMapping("/configTest")
        36. public Map configTest() {
        37. HashMap map = Maps.newHashMap();
        38. map.put("name", name);
        39. map.put("age", age);
        40. map.put("shared1", shared1);
        41. map.put("shared2", shared2);
        42. map.put("extension1", extension1);
        43. map.put("extension2", extension2);
        44. return map;
        45. }
        46. }

    • 登录Nacos控制台,添加nacos-config-dev.yml(DEFAULT_GROUP)、nacos-config-extension1.yml(EXTENSION1_GROUP)、nacos-config-extension2.yml(EXTENSION2_GROUP)、nacos-config-shared1.yml、(SHARED1_GROUP)nacos-config-shared2.yml(SHARED1_GROUP)配置。
      1. #nacos-config-dev.yml
      2. user:
      3. name: zhihong.zhu
      4. age: 288
      5. #nacos-config-extension1.yml
      6. user:
      7. name: zhihong.zhu
      8. age: 288
      9. extension1: extension11
      10. #nacos-config-extension2.yml
      11. user:
      12. name: zhihong.zhu
      13. age: 289
      14. extension2: extension22
      15. #nacos-config-shared1.yml
      16. user:
      17. name: zhihong.zhu
      18. age: 28
      19. shared1: shared1
      20. #nacos-config-shared2.yml
      21. user:
      22. name: zhihong.zhu
      23. age: 28
      24. shared2: shared2

    • 启动服务,调用接口http://localhost:18082/configTest查询配置。多次修改配置文件多次访问。可验证动态刷新配置及优先级。

    第四章:Nacos Gateway——API网关

    • Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。
    • 创建alibaba-spring-cloud-gateway子工程,添加依赖。
      1. <parent>
      2. <groupId>com.cloudgroupId>
      3. <artifactId>alibaba-spring-cloudartifactId>
      4. <version>1.0-SNAPSHOTversion>
      5. <relativePath>../pom.xmlrelativePath>
      6. parent>
      7. <properties>
      8. <java.version>1.8java.version>
      9. properties>
      10. <dependencies>
      11. <dependency>
      12. <groupId>com.alibaba.cloudgroupId>
      13. <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
      14. dependency>
      15. <dependency>
      16. <groupId>org.springframework.cloudgroupId>
      17. <artifactId>spring-cloud-starter-gatewayartifactId>
      18. dependency>
      19. <dependency>
      20. <groupId>org.springframework.bootgroupId>
      21. <artifactId>spring-boot-starter-actuatorartifactId>
      22. dependency>
      23. dependencies>

    • application.yml配置文件添加配置。
      1. server:
      2. port: 18083
      3. spring:
      4. application:
      5. name: nacos-gateway
      6. cloud:
      7. nacos:
      8. discovery:
      9. server-addr: 127.0.0.1:8848
      10. username: nacos
      11. password: nacos
      12. gateway:
      13. discovery:
      14. locator:
      15. enabled: true
      16. routes:
      17. - id: nacos-route
      18. uri: lb://provider-service
      19. predicates:
      20. - Path=/nacos/**
      21. filters:
      22. - StripPrefix=1
      23. management:
      24. endpoints:
      25. web:
      26. exposure:
      27. include: "*"
      28. endpoint:
      29. health:
      30. show-details: always

    • 配置属性说明:
      • routes——路由配置。
      • id——路由ID。
      • uri——路由指向地址。lb://是注册中心匹配方式,将从注册中心找对应的服务,所以注册中心必须有该服务。对服务命名方式有特殊要求。命名规则为:"[a-zA-Z]([a-zA-Z]|\\d|\\+|\\.|-)*:.*"。还有两种分别是ws(websocket)方式和http方式。
      • predicates——断言。
      • Path——与此值相匹配的路径进行路由。除此之外,断言有很多种路由方式。
      • filters——拦截。
      • StripPrefix——匹配路径的节数。
    • 启动服务,访问http://localhost:18083/nacos/echo/hello-world。实际会指向http://provider-service/echo/hello-world

    第五章:Sentinel——流控、熔断、降级

    • 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 https://github.com/alibaba/Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
    • 启动Sentinel 控制台。
      • 源码下载,下载地址https://gitee.com/mirrors/Sentinel/repository/archive/1.8.5
      • 解压进入文件根目录,编辑pom.xml,配置本地及alibaba的maven仓库地址保存。(file://xxx/Repository改为自己本地仓库位置)
        1. <repositories>
        2. <repository>
        3. <id>Localhostid>
        4. <name>Localhostname>
        5. <url>file://xxx/Repositoryurl>
        6. repository>
        7. <repository>
        8. <id>alimavenid>
        9. <name>aliyun mavenname>
        10. <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
        11. <releases>
        12. <enabled>trueenabled>
        13. releases>
        14. <snapshots>
        15. <enabled>falseenabled>
        16. snapshots>
        17. repository>
        18. repositories>
        19. <pluginRepositories>
        20. <pluginRepository>
        21. <id>alimavenid>
        22. <name>aliyun mavenname>
        23. <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
        24. <releases>
        25. <enabled>trueenabled>
        26. releases>
        27. <snapshots>
        28. <enabled>falseenabled>
        29. snapshots>
        30. pluginRepository>
        31. <pluginRepository>
        32. <id>Localhostid>
        33. <name>Localhostname>
        34. <url>file://xxx/Repositoryurl>
        35. pluginRepository>
        36. pluginRepositories>

      • 进入cmd,执行mvn -Dmaven.test.skip=true clean package命令进行编译。
      • 编译完成,进入Sentinel-1.8.5\sentinel-dashboard,打开cmd,执行java -Dserver.port=8868 -Dcsp.sentinel.dashboard.server=localhost:8868 -Dproject.name=sentinel-dashboard -jar target/sentinel-dashboard.jar命令启动。
      • 启动之后,打开浏览器访问http://127.0.0.1:8868访问控制台,输入账号密码sentinel登录进如控制台。
      • Sentinel控制台启动完成。
    • 创建alibaba-spring-cloud-sentinel子工程,添加依赖。
      1. <parent>
      2. <groupId>com.cloudgroupId>
      3. <artifactId>alibaba-spring-cloudartifactId>
      4. <version>1.0-SNAPSHOTversion>
      5. <relativePath>../pom.xmlrelativePath>
      6. parent>
      7. <properties>
      8. <java.version>1.8java.version>
      9. properties>
      10. <dependencies>
      11. <dependency>
      12. <groupId>org.springframework.bootgroupId>
      13. <artifactId>spring-boot-starter-webartifactId>
      14. dependency>
      15. <dependency>
      16. <groupId>com.alibaba.cloudgroupId>
      17. <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
      18. dependency>
      19. <dependency>
      20. <groupId>org.springframework.bootgroupId>
      21. <artifactId>spring-boot-starter-actuatorartifactId>
      22. dependency>
      23. <dependency>
      24. <groupId>com.alibaba.cspgroupId>
      25. <artifactId>sentinel-datasource-nacosartifactId>
      26. dependency>
      27. <dependency>
      28. <groupId>org.springframework.cloudgroupId>
      29. <artifactId>spring-cloud-starter-openfeignartifactId>
      30. dependency>
      31. <dependency>
      32. <groupId>com.alibaba.cloudgroupId>
      33. <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
      34. dependency>
      35. <dependency>
      36. <groupId>com.fasterxml.jackson.dataformatgroupId>
      37. <artifactId>jackson-dataformat-xmlartifactId>
      38. dependency>
      39. <dependency>
      40. <groupId>com.alibaba.cloudgroupId>
      41. <artifactId>spring-cloud-alibaba-sentinel-datasourceartifactId>
      42. dependency>
      43. dependencies>

    • application.yml配置文件添加配置。
      1. server:
      2. port: 18086
      3. spring:
      4. application:
      5. name: nacos-sentinel
      6. cloud:
      7. sentinel:
      8. transport:
      9. dashboard: localhost:8868
      10. eager: true
      11. web-context-unify: true
      12. filter:
      13. enabled: false
      14. http-method-specify: false
      15. datasource:
      16. # ds6:
      17. # nacos:
      18. # server-addr: 127.0.0.1:8848
      19. # username: nacos
      20. # password: nacos
      21. # dataId: flowrule.json
      22. # data-type: json
      23. # rule-type: flow
      24. ds1:
      25. file:
      26. file: "classpath: flowrule.xml"
      27. data-type: xml
      28. rule-type: flow
      29. ds2:
      30. file:
      31. file: "classpath: degraderule.json"
      32. data-type: json
      33. rule-type: degrade
      34. ds3:
      35. file:
      36. file: "classpath: authority.json"
      37. rule-type: authority
      38. ds4:
      39. file:
      40. file: "classpath: system.json"
      41. rule-type: system
      42. ds5:
      43. file:
      44. file: "classpath: param-flow.json"
      45. rule-type: param_flow
      46. management:
      47. endpoints:
      48. web:
      49. exposure:
      50. include: "*"
      51. feign:
      52. sentinel:
      53. enabled: true

    • 配置属性说明:
      • eager——是否提前触发 Sentinel 初始化。
      • web-context-unify——是否根据不同的URL 进行链路限流。
    • 添加文件到resources。文件地址https://gitee.com/zzh13520704819/sentinel-config.git
    • 文件说明:
      • authority.json——授权规则。
      • degraderule.json——熔断降级规则。
      • flowrule.json——流控规则。
      • flowrule.json——流控规则,xml数据类型配置。
      • param-flow.json——热点规则。
      • system.json——系统规则。
    • 文件属性说明:
      • 限流规则配置:
        |属性|说明|
        |:----|
        |app |应用名|
        |resource |资源名(唯一名称,默认请求路径)|
        |limitApp |针对来源 (Sentinel可以针对调用者进行限流,填写微服务名,指定对哪个微服务进行限流 ,默认default(不区分来源,全部限制))|
        |grade |阈值类型(阀值类型,0:线程数,1:QPS)|
        |count|单机阀值|
        |clusterMode|是否集群(false:否,true:是)|
        |controlBehavior|流控效果 (0:失败,1:warmUp,2:排队等待)
        |strategy|流控模式(0:直接,1:关联,2:链路)|
        |clusterConfig|thresholdType: 0|
        降级规则配置:
        |属性|说明|
        |:----|
        |app |应用名|
        |count |熔断策略为慢调用比例:最大Rt(需要设置的阈值,超过该值则为慢应用),异常比例中为:比例阈值,异常数中为:异常数|
        |limitApp |针对来源 (Sentinel可以针对调用者进行限流,填写微服务名,指定对哪个微服务进行限流 ,默认default(不区分来源,全部限制))|
        |grade |熔断策略(0:慢调用比例,1:异常比例,2:异常数)|
        |minRequestAmount|最小请求数(允许通过的最小请求数,在该数量内不发生熔断)|
        |timeWindow|熔断时长(在这段时间内发生熔断,拒绝所有请求)|
        |slowRatioThreshold|比例阈值 (慢调用占所有的调用比率,范围[0~1])
        |resource |资源名(唯一名称,默认请求路径)|
        |statIntervalMs |熔断时长(熔断时长,默认为1秒)|
        热点规则配置:
        |属性|说明|
        |:----|
        |app |应用名|
        |resource |资源名(唯一名称,默认请求路径)|
        |limitApp |针对来源 (Sentinel可以针对调用者进行限流,填写微服务名,指定对哪个微服务进行限流 ,默认default(不区分来源,全部限制))|
        |grade |限流模式(0:线程数,1:QPS)|
        |count|单机阀值|
        |durationInSec|统计窗口时间||
        |clusterMode|是否集群(false:否,true:是)|
        |paramIdx|参数索引|
        |paramFlowItemList|参数例外项,可以针对指定的参数值单独设置限流阈值,不受前面 count 阈值的限制。仅支持基本类型|
        |controlBehavior|流控效果,默认为0 (0:快速失败,1:warmUp,2:排队等待)
        |maxQueueingTimeMs|最大排队等待时长,默认0(仅在匀速排队模式生效)|
        授权规则配置:
        |属性|说明|
        |:----|
        |app |应用名|
        |resource|资源名|
        |limitApp |流控应用(指调用方,多个调用方名称用半角英文逗号(,)分隔)|
        |strategy |授权类型(0:白名单,1:黑名单)|
        系统规则配置:
        |属性|说明|
        |:----|
        |app |应用名|
        |highestSystemLoad |阈值(阈值类型为Load的阈值)[0,1)的正整数|
        |avgRt |阈值(阈值类型为RT的阈值)所有入口流量的平均响应时间,[0,1)的正整数|
        |maxThread |阈值(阈值类型为线程数的阈值)入口流量的最大并发数,[0,1)的正整数|
        |qps|阈值 (阈值类型为入口 QPS的阈值)所有入口资源的 QPS,[0,1)的正整数|
        |highestCpuUsage|阈值(阈值类型为CPU 使用率的阈值)[0,1]的小数,代表百分比|
    • 启动类添加@EnableDiscoveryClient注解。
    • 启动服务,查看sentinel控制台,可以看到各项配置已通过本地文件自动创建。
    • 可以继续在控制台创建各种规则。
    • 流控规则测试:
      • 创建SentinelController类,添加test方法。
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.commons.lang.StringUtils;
        3. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        4. import org.springframework.web.bind.annotation.GetMapping;
        5. import org.springframework.web.bind.annotation.PathVariable;
        6. import org.springframework.web.bind.annotation.RestController;
        7. import org.springframework.web.client.RestTemplate;
        8. import javax.annotation.Resource;
        9. import javax.servlet.http.HttpServletRequest;
        10. import java.util.Arrays;
        11. /**
        12. * 项目名称: consumer
        13. * 包名称: com.cloud.controller
        14. * 类名称: SentinelController {
        15. * 类描述:
        16. * 创建人: zhihong.zhu
        17. * 创建时间: 2022/8/15 14:12
        18. * 修改人:
        19. * 修改时间:
        20. * 修改备注:
        21. */
        22. @RestController
        23. public class SentinelController {
        24. @GetMapping("/test")
        25. @SentinelResource(value = "test")
        26. public String test(){
        27. return "Hello test";
        28. }
        29. }

      • 启动服务,访问http://localhost:18086/test,QPS超过1触发流控规则。
      • 响应的信息可以看出,触发流控规则后直接返回状态码为500的错误信息,不够友好,太过笼统,所以我们可以利用注解的一些属性自由处理一些可选的异常。
      • 创建ExceptionUtil类,添加blockException方法。
        1. package com.cloud.configurer;
        2. import com.alibaba.csp.sentinel.slots.block.BlockException;
        3. public final class ExceptionUtil {
        4. private ExceptionUtil() {
        5. }
        6. public static String blockException(BlockException ex) {
        7. System.out.println("Oops: " + ex.getClass().getCanonicalName());
        8. return ex.getClass().getCanonicalName();
        9. }
        10. }

      • SentinelController类的test的@SentinelResource注解添加blockHandler = "blockException",blockHandlerClass = ExceptionUtil.class属性。
        1. package com.cloud.controller;
        2. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        3. import com.cloud.configurer.ExceptionUtil;
        4. import org.springframework.beans.factory.annotation.Autowired;
        5. import org.springframework.web.bind.annotation.GetMapping;
        6. import org.springframework.web.bind.annotation.RestController;
        7. import org.springframework.web.client.RestTemplate;
        8. /**
        9. * 项目名称: sentinel
        10. * 包名称: com.cloud.controller
        11. * 类名称: SentinelController
        12. * 类描述:
        13. * 创建人: zhihong.zhu
        14. * 创建时间: 2022/8/12 14:56
        15. * 修改人:
        16. * 修改时间:
        17. * 修改备注:
        18. */
        19. @RestController
        20. public class SentinelController {
        21. @GetMapping("/test")
        22. @SentinelResource(value = "test",
        23. blockHandler = "blockException",
        24. blockHandlerClass = ExceptionUtil.class)
        25. public String test(){
        26. return "Hello test";
        27. }
        28. }

      • 注解属性说明:
        • blockHandler——异常处理方法名称。
        • blockHandlerClass——异常处理类。(如果和主方法在同一类里,可省略此属性,如果不在则必须添加此属性)
        • 异常处理方法返回类型需要与原方法相匹配,参数类型需要和原方法相匹配并且最后加一个额外的参数,类型为BlockException。
      • 启动服务访问http://localhost:18086/test,QPS超过1触发流控规则。并返回处理后的数据。
      • 响应中文乱码处理:添加mvc配置类如下
        1. package com.cloud.configurer;
        2. import com.alibaba.fastjson.serializer.SerializerFeature;
        3. import com.alibaba.fastjson.support.config.FastJsonConfig;
        4. import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
        5. import org.springframework.context.annotation.Configuration;
        6. import org.springframework.http.MediaType;
        7. import org.springframework.http.converter.HttpMessageConverter;
        8. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
        9. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
        10. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
        11. import java.nio.charset.Charset;
        12. import java.util.Arrays;
        13. import java.util.List;
        14. /**
        15. * @author yuhuangbin
        16. */
        17. @Configuration
        18. @EnableWebMvc
        19. public class WebMvcConfiguration implements WebMvcConfigurer {
        20. // 使用阿里 FastJson 作为JSON MessageConverter
        21. @Override
        22. public void configureMessageConverters(List> converters) {
        23. FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        24. FastJsonConfig config = new FastJsonConfig();
        25. config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, // 集合为null时返回空集合
        26. SerializerFeature.WriteMapNullValue, // 保留空的字段
        27. SerializerFeature.WriteDateUseDateFormat,// 使用时间转换
        28. SerializerFeature.WriteNullStringAsEmpty);//String null -> ""
        29. // SerializerFeature.WriteNullNumberAsZero//Number null -> 0
        30. // 按需配置,更多参考FastJson文档
        31. // config.setParserConfig();
        32. converter.setFastJsonConfig(config);
        33. // converter.setDateFormat("yyyy-MM-dd HH:mm:ss");
        34. converter.setDefaultCharset(Charset.forName("UTF-8"));
        35. converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
        36. converters.add(0, converter);
        37. }
        38. }

    • 熔断降级规则测试:
      • SentinelController添加test2方法:
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.commons.lang.StringUtils;
        3. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        4. import com.cloud.configurer.ExceptionUtil;
        5. import com.cloud.configurer.SentinelFallbackFactory;
        6. import org.springframework.web.bind.annotation.GetMapping;
        7. import org.springframework.web.bind.annotation.PathVariable;
        8. import org.springframework.web.bind.annotation.RestController;
        9. /**
        10. * 项目名称: sentinel
        11. * 包名称: com.cloud.controller
        12. * 类名称: SentinelController
        13. * 类描述:
        14. * 创建人: zhihong.zhu
        15. * 创建时间: 2022/8/12 14:56
        16. * 修改人:
        17. * 修改时间:
        18. * 修改备注:
        19. */
        20. @RestController
        21. public class SentinelController {
        22. @GetMapping("/test")
        23. @SentinelResource(value = "test",
        24. blockHandler = "blockException",
        25. blockHandlerClass = ExceptionUtil.class)
        26. public String test(){
        27. return "Hello test";
        28. }
        29. @GetMapping("/test2/{p1}")
        30. @SentinelResource(value = "abc0",
        31. fallback = "test2Fallback",
        32. fallbackClass = SentinelFallbackFactory.class)
        33. public String test2(@PathVariable String p1){
        34. if (StringUtils.equals("1",p1)){
        35. throw new RuntimeException("参数为1导致异常");
        36. }
        37. return "Hello(你好) test1-"+p1;
        38. }
        39. }

      • 创建熔断处理类SentinelFallbackFactory,添加test2Fallback方法:
        1. package com.cloud.configurer;
        2. import org.springframework.web.bind.annotation.PathVariable;
        3. /**
        4. * 项目名称: sentinel
        5. * 包名称: com.cloud.configurer
        6. * 类名称: SentinelFallbackFactory
        7. * 类描述:
        8. * 创建人: zhihong.zhu
        9. * 创建时间: 2022/8/15 14:17
        10. * 修改人:
        11. * 修改时间:
        12. * 修改备注:
        13. */
        14. public class SentinelFallbackFactory {
        15. public static String test2Fallback(@PathVariable String p1,Throwable throwable) {
        16. return "触发熔断"+throwable.getMessage();
        17. }
        18. }

      • 注解属性说明:
        • value——规则资源名称。(此资源通过本地规则文件已配置,可通过控制台查看此资源规则配置)
        • fallback——熔断后处理方法。(该方法必须为静态方法,可以额外多一个 Throwable 类型的参数用于接收对应的异常。)
        • fallbackClass——熔断处理类。(如果和主方法在同一类里,可省略此属性,如果不在则必须添加此属性)
        • 熔断处理方法返回类型需要与原方法相匹配,参数类型需要和原方法相匹配。
      • 启动服务访问http://localhost:18086/test2/1,返回熔断及异常信息。
    • 热点参数规则测试:
      • 热点参数规则是一种精准的流控规则,它允许将规则绑定到参数上。比如方法有两个参数,我们对第一个参数进行限流,对第二个参数不限流。
      • SentinelController添加test3方法:
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.commons.lang.StringUtils;
        3. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        4. import com.cloud.configurer.ExceptionUtil;
        5. import com.cloud.configurer.SentinelFallbackFactory;
        6. import org.springframework.web.bind.annotation.GetMapping;
        7. import org.springframework.web.bind.annotation.PathVariable;
        8. import org.springframework.web.bind.annotation.RestController;
        9. /**
        10. * 项目名称: sentinel
        11. * 包名称: com.cloud.controller
        12. * 类名称: SentinelController
        13. * 类描述:
        14. * 创建人: zhihong.zhu
        15. * 创建时间: 2022/8/12 14:56
        16. * 修改人:
        17. * 修改时间:
        18. * 修改备注:
        19. */
        20. @RestController
        21. public class SentinelController {
        22. @GetMapping("/test")
        23. @SentinelResource(value = "test",
        24. blockHandler = "blockException",
        25. blockHandlerClass = ExceptionUtil.class)
        26. public String test(){
        27. return "Hello test";
        28. }
        29. @GetMapping("/test2/{p1}")
        30. @SentinelResource(value = "abc0",
        31. fallback = "test2Fallback",
        32. fallbackClass = SentinelFallbackFactory.class)
        33. public String test2(@PathVariable String p1){
        34. if (StringUtils.equals("1",p1)){
        35. throw new RuntimeException("参数为1导致异常");
        36. }
        37. return "Hello(你好) test1"+p1;
        38. }
        39. @GetMapping("/test3/{p1}/{p2}")
        40. @SentinelResource(value = "aa",
        41. blockHandler = "test3BlockException",
        42. blockHandlerClass = ExceptionUtil.class)
        43. public String test3(@PathVariable String p1,@PathVariable String p2){
        44. return "Hello(你好) test3-p1="+p1+"p2="+p2;
        45. }
        46. }

      • ExceptionUtil类添加test3BlockException方法:
        1. package com.cloud.configurer;
        2. import com.alibaba.csp.sentinel.slots.block.BlockException;
        3. public final class ExceptionUtil {
        4. private ExceptionUtil() {
        5. }
        6. public static String blockException(BlockException ex) {
        7. System.out.println("Oops: " + ex.getClass().getCanonicalName());
        8. return ex.getClass().getCanonicalName();
        9. }
        10. public static String test3BlockException(String p1,String p2,BlockException ex) {
        11. System.out.println("Oops: " + ex.getClass().getCanonicalName());
        12. return ex.getClass().getCanonicalName();
        13. }
        14. }

      • 热点流控规则说明:
        • 查看Sentinel控制台的热点规则可知:
          • 参数索引=0——第一个参数。
          • 单机阀值=0——QPS超过0触发规则。
      • 启动服务访问http://localhost:18086/test3/1/2,QPS超过1触发流控规则。并返回处理后的数据。
    • 授权规则测试:
      • Sentinel提供了RequestOriginParser接口来处理来源。如果Sentinel保护的资源被访,Sentinel就会调用RequestOriginParser的实现类去处理访问来源。
      • SentinelController添加test4方法:
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.commons.lang.StringUtils;
        3. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        4. import com.cloud.configurer.ExceptionUtil;
        5. import com.cloud.configurer.SentinelFallbackFactory;
        6. import org.springframework.web.bind.annotation.GetMapping;
        7. import org.springframework.web.bind.annotation.PathVariable;
        8. import org.springframework.web.bind.annotation.RestController;
        9. import javax.servlet.http.HttpServletRequest;
        10. /**
        11. * 项目名称: sentinel
        12. * 包名称: com.cloud.controller
        13. * 类名称: SentinelController
        14. * 类描述:
        15. * 创建人: zhihong.zhu
        16. * 创建时间: 2022/8/12 14:56
        17. * 修改人:
        18. * 修改时间:
        19. * 修改备注:
        20. */
        21. @RestController
        22. public class SentinelController {
        23. @GetMapping("/test")
        24. @SentinelResource(value = "test",
        25. blockHandler = "blockException",
        26. blockHandlerClass = ExceptionUtil.class)
        27. public String test() {
        28. return "Hello test";
        29. }
        30. @GetMapping("/test2/{p1}")
        31. @SentinelResource(value = "abc0",
        32. fallback = "test2Fallback",
        33. fallbackClass = SentinelFallbackFactory.class)
        34. public String test2(@PathVariable String p1) {
        35. if (StringUtils.equals("1", p1)) {
        36. throw new RuntimeException("参数为1导致异常");
        37. }
        38. return "Hello(你好) test1" + p1;
        39. }
        40. @GetMapping("/test3/{p1}/{p2}")
        41. @SentinelResource(value = "aa",
        42. blockHandler = "test3BlockException",
        43. blockHandlerClass = ExceptionUtil.class)
        44. public String test3(@PathVariable String p1, @PathVariable String p2) {
        45. return "Hello(你好) test3-p1=" + p1 + "p2=" + p2;
        46. }
        47. @GetMapping("/test4")
        48. @SentinelResource(value = "bad",
        49. blockHandler = "test4BlockException",
        50. blockHandlerClass = ExceptionUtil.class)
        51. public String test4(HttpServletRequest request) {
        52. return "Hello(你好) test4-p1=" + request.getParameter("p1");
        53. }
        54. }

      • 创建MyRequestOriginParser类实现RequestOriginParser接口类:
        1. package com.cloud.configurer;
        2. import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
        3. import org.springframework.stereotype.Component;
        4. import javax.servlet.http.HttpServletRequest;
        5. /**
        6. * 项目名称: sentinel
        7. * 包名称: com.cloud.configurer
        8. * 类名称: MyRequestOriginParser
        9. * 类描述: 自定义来源处理规则
        10. * 创建人: zhihong.zhu
        11. * 创建时间: 2022/8/15 16:40
        12. * 修改人:
        13. * 修改时间:
        14. * 修改备注:
        15. */
        16. @Component
        17. public class MyRequestOriginParser implements RequestOriginParser {
        18. @Override
        19. public String parseOrigin(HttpServletRequest request) {
        20. return request.getParameter("p1");
        21. }
        22. }

      • 授权规则说明:
        • 查看Sentinel控制台的热点规则可知:
          • 资源名=bad——规则资源名称。
          • 流控应用=bcd——资源bad参数p1=bcd。
          • 授权类型=黑名单——资源bad参数p1=bcd时无法访问(黑名单)
      • 注意:如果配置文件spring.cloud.sentinel.filter.enabled=false,授权规则不生效。
      • 启动服务访问http://localhost:18086/test4?p1=bcd,触发授权规则。并返回处理后的数据。
    • OpenFeign 支持
      • SentinelController添加test5方法:
        1. package com.cloud.controller;
        2. import com.alibaba.cloud.commons.lang.StringUtils;
        3. import com.alibaba.csp.sentinel.annotation.SentinelResource;
        4. import com.cloud.configurer.ExceptionUtil;
        5. import com.cloud.configurer.SentinelFallbackFactory;
        6. import com.cloud.service.SentinelService;
        7. import org.springframework.beans.factory.annotation.Autowired;
        8. import org.springframework.web.bind.annotation.GetMapping;
        9. import org.springframework.web.bind.annotation.PathVariable;
        10. import org.springframework.web.bind.annotation.RestController;
        11. import javax.servlet.http.HttpServletRequest;
        12. /**
        13. * 项目名称: sentinel
        14. * 包名称: com.cloud.controller
        15. * 类名称: SentinelController
        16. * 类描述:
        17. * 创建人: zhihong.zhu
        18. * 创建时间: 2022/8/12 14:56
        19. * 修改人:
        20. * 修改时间:
        21. * 修改备注:
        22. */
        23. @RestController
        24. public class SentinelController {
        25. @Autowired
        26. private SentinelService sentinelService;
        27. @GetMapping("/test")
        28. @SentinelResource(value = "test",
        29. blockHandler = "blockException",
        30. blockHandlerClass = ExceptionUtil.class)
        31. public String test() {
        32. return "Hello test";
        33. }
        34. @GetMapping("/test2/{p1}")
        35. @SentinelResource(value = "abc0",
        36. fallback = "test2Fallback",
        37. fallbackClass = SentinelFallbackFactory.class)
        38. public String test2(@PathVariable String p1) {
        39. if (StringUtils.equals("1", p1)) {
        40. throw new RuntimeException("参数为1导致异常");
        41. }
        42. return "Hello(你好) test1" + p1;
        43. }
        44. @GetMapping("/test3/{p1}/{p2}")
        45. @SentinelResource(value = "aa",
        46. blockHandler = "test3BlockException",
        47. blockHandlerClass = ExceptionUtil.class)
        48. public String test3(@PathVariable String p1, @PathVariable String p2) {
        49. return "Hello(你好) test3-p1=" + p1 + "p2=" + p2;
        50. }
        51. @GetMapping("/test4")
        52. @SentinelResource(value = "bad",
        53. blockHandler = "test4BlockException",
        54. blockHandlerClass = ExceptionUtil.class)
        55. public String test4(HttpServletRequest request) {
        56. return "Hello(你好) test4-p1=" + request.getParameter("p1");
        57. }
        58. @GetMapping("/test5/{p1}")
        59. public String test5(@PathVariable String p1) {
        60. return sentinelService.echo(p1);
        61. }
        62. }

      • 创建SentinelService接口类,添加echo方法:
        1. package com.cloud.service;
        2. import com.cloud.configurer.FeignFallbackFactory;
        3. import org.springframework.cloud.openfeign.FeignClient;
        4. import org.springframework.web.bind.annotation.GetMapping;
        5. import org.springframework.web.bind.annotation.PathVariable;
        6. @FeignClient(name = "provider-service",fallbackFactory = FeignFallbackFactory.class)
        7. public interface SentinelService {
        8. @GetMapping("/echo/{string}")
        9. String echo(@PathVariable String string);
        10. }

      • 创建FeignFallbackFactory类,实现FallbackFactory接口,重写方法:
        1. package com.cloud.configurer;
        2. import com.cloud.service.SentinelService;
        3. import org.springframework.cloud.openfeign.FallbackFactory;
        4. import org.springframework.stereotype.Component;
        5. /**
        6. * 项目名称: sentinel
        7. * 包名称: com.cloud.service
        8. * 类名称: FeignFallbackFactory
        9. * 类描述:
        10. * 创建人: zhihong.zhu
        11. * 创建时间: 2022/8/15 14:17
        12. * 修改人:
        13. * 修改时间:
        14. * 修改备注:
        15. */
        16. @Component
        17. public class FeignFallbackFactory implements FallbackFactory {
        18. @Override
        19. public SentinelService create(Throwable throwable) {
        20. return new SentinelService() {
        21. @Override
        22. public String echo(String str) {
        23. return throwable.getClass().getCanonicalName();
        24. }
        25. };
        26. }
        27. }

      • pom.xml添加依赖:
        1. <dependency>
        2. <groupId>org.springframework.cloudgroupId>
        3. <artifactId>spring-cloud-starter-loadbalancerartifactId>
        4. dependency>

      • 启动类添加@EnableFeignClients注解。
      • 修改provider-service服务的echo接口,添加错误代码抛出异常。
      • 启动provider-service服务和该服务访问http://localhost:18086/test5/sentinel,触发熔断降级处理。

    以上为入门实战的一些操作,如有初学者按照上面方式操作发现问题,请留言,看到后会修正解决。

    想了解更多建议看相关源码:https://gitee.com/mirrors/Spring-Cloud-Alibaba/repository/archive/2021.0.1.0 

  • 相关阅读:
    zookeeper没有.log日志,只有.out日志
    【Python+Appium】开展自动化测试(5)appium元素定位常用方法
    java毕业设计开题报告论文基于JavaWeb项目实现的高校学生在线选课系统
    3D模型如何添加表面贴图?
    Jenkins从入门到精通面试题及参考答案(3万字长文)
    Redis-哨兵模式(sentinel)
    mysql 触发器
    使用 Ubuntu + Docker + Vaultwarden + Tailscale 自建密码管理器
    G1 收集器
    FPGA实现AXI4总线的读写_如何写axi4逻辑
  • 原文地址:https://blog.csdn.net/tomcat_zhu/article/details/126760632