SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化

sentinel

  • 1.服务熔断功能
    • 1.1Ribbon restTemplate 限流、降级
      • 1.1.1新建cloudalibaba-provider-payment9005/9006
      • 1.1.2新建 alibaba-consumer-nacos-order84
      • 1.1.3 依次启动 9005/9006-->84 测试
    • 1.2.openFeign 接口 限流、降级
      • 1.2.1修改 alibaba-consumer-nacos-order84
      • 1.2.2测试
  • 2.持久化 配置
    • 2.1pom添加
    • 2.2http://localhost:8848/nacos/ Nacos业务规则配置
    • 2.3在Sentinel 控制台配置
    • 2.4重新启动84 http://localhost:84/consumer/ok 后

SpringCloud Alibaba使用(一) - Nacos服务注册、配置中心、集群和持久化
SpringCloud Alibaba使用(二) - sentinel 流控规则、降级规则、热点key限流、系统规则、@SentinelResource
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化
SpringCloud Alibaba使用(四) - seata分布式事务

1.服务熔断功能

1.1Ribbon restTemplate 限流、降级

1.1.1新建cloudalibaba-provider-payment9005/9006

pom

<dependencies>
        <dependency>
            <groupId>com.psf.spirngcloud.Alibaba</groupId>
            <artifactId>alibaba-psf-basic</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <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>
        <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>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>

yml

server:
  port: 9005
spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
        #server-addr: 192.168.2.100:1111 #配置Nacos地址  集群测试
        ip: localhost
management:
  endpoints:
    web:
      exposure:
        include: '*'

启动

@EnableDiscoveryClient
@SpringBootApplication
public class ProviderNacosMain9005 {

    public static void main(String[] args) {
        SpringApplication.run(ProviderNacosMain9005.class,args);
    }
}

业务类

@RestController
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    public static HashMap<Long, User> hashMap = new HashMap<>();

    static {
        hashMap.put(1L, new User(1L, "111111"));
        hashMap.put(2L, new User(2L, "222222"));
        hashMap.put(3L, new User(3L, "333333"));
    }

    @GetMapping("/result/{id}")
    public CommonResult getResult(@PathVariable Long id) {
        User user = hashMap.get(id);
        CommonResult<User> userCommonResult = new CommonResult<>(
                200, "serverPort:" + serverPort, user
        );
        return userCommonResult;
    }
}

1.1.2新建 alibaba-consumer-nacos-order84

pom

  <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>com.psf.spirngcloud.Alibaba</groupId>
            <artifactId>alibaba-psf-basic</artifactId>
            <version>${project.version}</version>
        </dependency>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

yml

server:
  port: 84


spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        ip: localhost
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

service-url:
  nacos-user-service: http://nacos-payment-provider


启动类

@SpringBootApplication
@EnableDiscoveryClient //开启注册中心
@EnableFeignClients //启用feign客户端
public class ConsumerOrderMain84 {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerOrderMain84.class,args);
    }
}

业务类

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

    @Resource
    private RestTemplate restTemplate;

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

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

        return result;
    }
    //fallback
    public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {
        User payment = new User(id,"null");
        return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }

    //blockHandler
    public CommonResult handler(@PathVariable  Long id, BlockException blockException) {
        User payment = new User(id,"null");
        return new CommonResult<>(444,"被限速啦  "+blockException.getMessage(),payment);
    }
}

工具

@Configuration
public class ApplicationContextConfig {

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

1.1.3 依次启动 9005/9006–>84 测试

sentinel 设置 限制
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第1张图片
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第2张图片

执行 http://localhost:84/consumer/fallback/1
在这里插入图片描述
快速刷新:
在这里插入图片描述
执行4:
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第3张图片
执行5:
在这里插入图片描述

1.2.openFeign 接口 限流、降级

1.2.1修改 alibaba-consumer-nacos-order84

pom

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

yml

server:
  port: 84


spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

service-url:
  nacos-user-service: http://nacos-payment-provider

#对Feign的支持
feign:
  sentinel:
    enabled: true

添加@EnableFeignClients启动Feign的功能

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerOrderMain84 {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerOrderMain84.class,args);
    }
}

带@FeignClient注解的业务接口

//value 找9005/9006 spring:application:name:
@FeignClient(value ="nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {

    //接口对应9004/9005
    @GetMapping(value = "/result/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id);
}

fallback = PaymentFallbackService.class 兜底方法

@Component
public class PaymentFallbackService implements PaymentService{
    @Override
    public CommonResult getPayment(Long id) {

        return new CommonResult(404,"openFeign异常兜底",new User(id,null));
    }
}

Controller

@RestController
@Slf4j
public class OpenFeignController {

    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        return paymentService.getPayment(id);
    }
}

1.2.2测试

http://localhost:84/consumer/1
在这里插入图片描述
关闭9005/9006 不会被耗死
在这里插入图片描述
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第4张图片

2.持久化 配置

2.1pom添加

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
server:
  port: 84


spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        ip: localhost
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719
        #主要添加这里
       #----------------------------------
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: nacos-order-consumer
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow
       #----------------------------------
service-url:
  nacos-user-service: http://nacos-payment-provider
#对Feign的支持
feign:
  sentinel:
    enabled: true

2.2http://localhost:8848/nacos/ Nacos业务规则配置

SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第5张图片

[
    {
         "resource": "/consumer/ok",
         "limitApp": "default",
         "grade":   1,
         "count":   1,
         "strategy": 0,
         "controlBehavior": 0,
         "clusterMode": false    
    }
]

SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第6张图片

SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第7张图片

2.3在Sentinel 控制台配置

http://localhost:8080/
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第8张图片

2.4重新启动84 http://localhost:84/consumer/ok 后

sentinel 的配置还在
SpringCloud Alibaba使用(三) - sentinel fallback整合ribbon+openFeign 服务熔断功能 规则持久化_第9张图片

代码

你可能感兴趣的:(springcloud,Alibaba,sentinel,nacos)