Sentinel服务熔断实战(sentinel整合ribbon+openFeign+fallback)

举报
别团等shy哥发育 发表于 2022/04/23 15:57:13 2022/04/23
【摘要】 @toc源码地址:gitee仓库地址 1、Ribbon系列 1.1 启动nacos和sentinel 1.2 创建两个服务提供者payment9003和payment9004  新建cloudalibaba-provider-payment9003/9004两个一样的做法  由于9003和9004除了端口号不一样,其他几乎一致,这里只演示9003端口的搭建方式。  pom.xml <dep...

@toc

源码地址:gitee仓库地址

1、Ribbon系列

1.1 启动nacos和sentinel

image-20220416234815852

image-20220416234829591

1.2 创建两个服务提供者payment9003和payment9004

  新建cloudalibaba-provider-payment9003/9004两个一样的做法

image-20220416235040599

  由于9003和9004除了端口号不一样,其他几乎一致,这里只演示9003端口的搭建方式。

  pom.xml

  <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.atguigu.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>

  application.yml

 
server:
  port: 9003

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost: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

image-20220416235755999

  http://localhost:9004/paymentSQL/1

image-20220416235931322

   两个服务提供者搭建成功。

1.3 搭建服务消费者order84

1.3.1 基础模块搭建

  新建cloudalibaba-consumer-nacos-order84

image-20220417000034209

  pom.xml

<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.atguigu.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>

  application.yml

server:
  port: 84


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


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

  主启动类

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

  业务类

  负载均衡配置:

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

  CircleBreakerController

@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<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

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

        return result;
    }
}

  上面代码在id=1/2/3时正常,id=4时抛出IllegalArgumentException异常,大于4的时候抛出空指针异常。

  这里的测试目的:fallback管运行异常,blockHandler管配置违规

  上面并没有配置@SentinelResource,会直接给客户返回error页面,非常不友好。

1.3.2 只配置fallback

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

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

        return result;
    }

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

  注意:这里并没有配置sentinel。

  访问测试:

  http://localhost:84/consumer/fallback/1

image-20220417000937192

  http://localhost:84/consumer/fallback/4

image-20220417000956764

  http://localhost:84/consumer/fallback/5

image-20220417001012956

  此时就执行指定的fallback,对调用者比较友好。

1.3.3 只配置blockHandler

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

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

        return result;
    }

//    //fallback方法
//    public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {
//        Payment payment = new Payment(id,"null");
//        return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
//    }
//
    //blockHandler
    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

image-20220417001348466

image-20220417001420614

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

image-20220417001915291

  测试:

  第一次访问:http://localhost:84/consumer/fallback/4

image-20220417002558240

  发现还是给了个error页面,注意,我们上面配置的是当异常数大于2的时候断路器才会打开。

  再访问几次。

image-20220417002701266

   可以看到,被限流了。

1.3.4 fallback和blockHandler都配置

@RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")
//    @SentinelResource(value = "fallback",fallback = "handlerFallback")
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流
    @SentinelResource(value = "fallback",
            fallback = "handlerFallback",
            blockHandler = "blockHandler",
    )
    public CommonResult<Payment> fallback(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);

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

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

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

image-20220417002941407

   这里需要配置Sentinel流控

image-20220417003808238

  配置解释:1秒只能处理1个请求,否则就限流。

  我们测试,http://localhost:84/consumer/fallback/4,一直频繁访问触发限流降级。

image-20220417004423470

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

1.3.5 忽略属性配置

image-20220417004520079

  我们给@SentinelResource注解添加配置exceptionsToIgnore = {IllegalArgumentException.class}

  此时如果我们传的参数id=4,则会忽略IllegalArgumentException异常。

  此时再访问:http://localhost:84/consumer/fallback/4

image-20220417004715815

   此时异常打印到前台了,对用户不友好。

2、Feign系列

  我们一般服务调用都是使用OpenFeign的,在FeignClient中统一处理fallback

2.1 修改84模块。

  在服务消费者(order84)模块中引入OpenFeign

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

image-20220417005307090

2.2 配置文件application.yml中激活Sentinel对Feign的支持

image-20220417005354023

2.3 业务类

  带@FeignClient注解的业务接口

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

  fallback = PaymentFallbackService.class的实现类

@Component
public class PaymentFallbackService implements PaymentService
{
    @Override
    public CommonResult<Payment> paymentSQL(Long id)
    {
        return new CommonResult<>(44444444,"服务降级返回,-------PaymentFallbackService",new Payment(id, "errorSerial......"));
    }
}

  Controller:

image-20220417014201295

  主启动类

  添加@EnableFeignClients启动Feign的功能

image-20220417014252214

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

image-20220417014508218

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

  关闭9003的服务提供者

image-20220417014536417

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

image-20220417014600726

  可以看到,已经出发了服务降级。返回的是我们在FeignClient接口中指定的falback。

3、三种熔断框架比较

image-20220417014729090

  到此,Sentinel整合服务熔断的测试就介绍完了,关于Sentinel限流那块配置太多,不好细讲,最好去看看官网。我去年也发过限流的文章,去我SpringCloud Alibaba专栏里面找

【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。