广告位联系
返回顶部
分享到

SpringCloud hystrix断路器与全局解耦全面介绍

java 来源:互联网 作者:佚名 发布时间:2022-10-26 22:20:52 人浏览
摘要

第七章中在ProductController 和OrderController 中都使用了局部服务降级,但同时也导致两个问题, 通过观察两个局部降级的案例,可以发现: 每个业务方法都对应一个降级方法,会导致代码

第七章中在ProductController 和OrderController 中都使用了局部服务降级,但同时也导致两个问题, 通过观察两个局部降级的案例,可以发现:

每个业务方法都对应一个降级方法,会导致代码膨胀业务逻辑方法和处理服务异常降级方法混在一起。

业务逻辑方法和处理服务异常降级方法混在一起,不便于维护,为解决此问题,可以使用注解 @FeignClient(value = "PRODUCT-SERVICE",fallback = xxx.class)在调用远端服务的接口上进行指定服务降级方法解耦,并实现调用远端服务的接口的实现类,在实现类中统计管理服务降级解耦的方法。

进行全局解耦,以 订单服务 OrderController 调用 商品服务ProductController 为案例,过程如下:

1、订单服务 和 商品服务引入依赖

订单服务引入依赖 openfegin , 商品服务分别引入依赖 Hystrix

2、清除OrderController 和 ProductController 所有降级方法

清除OrderController 所有降级方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import com.hwadee.springcloud.entity.Product;

import com.hwadee.springcloud.service.IOrderFeignService;

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.RestController;

@RestController

@RequestMapping("/order")

public class OrderController {

    @Autowired

    IOrderFeignService orderFeignService;

    @RequestMapping("/buy/{id}")

    public Product buy(@PathVariable Long id) {

        System.out.println("进入OrderController的buy方法, orderFeignService 准备调用远端接口 findById");

        Product product = orderFeignService.findOrderById(id);

        return product;

    }

    @RequestMapping(value = "/delete/{id}")

    public Product deleteOrderById(@PathVariable Long id) {

        System.out.println("进入OrderController的deleteOrderById方法, orderFeignService 准备调用远端接口deleteOrderById");

        Product product = orderFeignService.deleteOrderById(id);

        return product;

    }

}

清除 ProductController 所有降级方法

注意,若有全局或者专属降级可以自己增加。此处为方便演示,不使用全局或者专属。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

import com.hwadee.springcloud.entity.Product;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController

@RequestMapping("/product")

public class ProductController {

    //方便后面讲负载均衡,查看ip,此处获取配置中的端口号和ip

    @Value("${server.port}")

    private String port;

    @Value("${spring.cloud.client.ip-address}")

    private String ip;

    @RequestMapping("/buy/{id}")

    public Product findById(@PathVariable Long id) {

        Product product = new Product();

        product.setId(id);

        // 后面需要测试负载均衡,所以返回 ip 地址及端口号

        product.setName("当前访问服务地址:" + ip + ":" + port + "  " + "查询商品订单,订单号:" + id);

        product.setPrice(new BigDecimal(10000.0));

        System.out.println(product);

        //测试超时熔断

        try {

            Thread.sleep(5000);

            //测试并发熔断

            //Thread.sleep(500);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        return product;

    }

    @RequestMapping(value = "/delete/{id}")

    public Product deleteOrderById(@PathVariable Long id) {

        Product product = new Product();

        product.setId(id);

        // 后面需要测试负载均衡,所以返回 ip 地址及端口号

        product.setName("当前访问服务地址:" + ip + ":" + port + "  " + "从购物车删除订单,订单号:" + id);

        product.setPrice(new BigDecimal(10000.0));

        System.out.println(product);

        //测试异常熔断

        System.out.println(10 / 0);

        return product;

    }

}

2、定义Feign接口的实现类

因为订单服务 OrderController中通过 接口IOrderFeignService和 注解@FeignClient 远程调用商品服务ProductController,因此当订单服务 OrderController出现超时或异常,可以通过订单服务 OrderController中通过 接口IOrderFeignService的 实现类OrderFeignServiceFallBack 将务逻辑的处理方法 和 降级方法进行解耦。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import com.hwadee.springcloud.entity.Product;

import com.hwadee.springcloud.service.IOrderFeignService;

import org.springframework.stereotype.Component;

@Component

public class OrderFeignServiceFallBack implements IOrderFeignService {

    @Override

    public Product findOrderById(Long id) {

        Product product = new Product();

        product.setId(id);

        product.setName("当前订单服务访问/order/buy/1 超时:"+id);

        return product;

    }

    @Override

    public Product deleteOrderById(Long id) {

        Product product = new Product();

        product.setId(id);

        product.setName("当前订单服务访问/order/delete/1 10/0异常:"+id);

        return product;

    }

}

3、修改IOrderFeignService代码

在 接口IOrderFeignService的注解@FeignClient中指定服务解耦的类OrderFeignServiceFallBack 。

1

2

3

4

5

6

7

8

@Component // 让 spring 可以识别,不加也行,但是在注入的时候 IDEA 会报错,不会影响运行,但有条红线让自己不舒服

@FeignClient(value = "PRODUCT-SERVICE",fallback = OrderFeignServiceFallBack.class)

public interface IOrderFeignService {

    @RequestMapping(value = "/product/buy/{id}")

    Product findOrderById(@PathVariable Long id);

    @RequestMapping(value = "/product/delete/{id}")

    Product deleteOrderById(@PathVariable Long id);

}

4、定义 订单服务 和 商品服务主启动类

由于订单服务中引入的spring-cloud-starter-openfeign依赖中已经集成了feign-hystrix,有了对 Hystrix 的支持,所以不需要额外引入依赖项。如果需要开启 订单服务端的hystrix服务,只需要在订单服务的配置文件配置feign-hystrix 进行激活Hystrix,无需在主启动类中添加注解 @EnableHystrix 或 @EnableHystrix 来开启Hystrix服务。订单服务 和 商品服务主启动类如下:

订单服务主启动类 OrderServerApplication

1

2

3

4

5

6

7

8

9

10

11

12

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication

@EnableEurekaClient// 启动 eureka 客户端

@EnableFeignClients  // 启动 feign

public class OrderServerApplication {

    public static void main(String[] args) {

        SpringApplication.run(OrderServerApplication.class, args);

    }

}

商品服务主启动类 ProductServerApplication

1

2

3

4

5

6

7

@SpringBootApplication

@EnableEurekaClient// 启动 eureka 客户端

public class ProductServerApplication {

    public static void main(String[] args) {

        SpringApplication.run(ProductServerApplication.class, args);

    }

}

4、开启openfeign在调用服务过程中开启hystrix支持

由于前面引入的spring-cloud-starter-openfeign依赖中已经集成了feign-hystrix,有了对 Hystrix 的支持,所以不需要额外引入依赖项。只需要在订单服务的 application.yml 配置文件中开启openfeign在调用服务过程中开启hystrix支持。

server:
  port: 9000
spring:
  application:
    name: order-service # 为当前订单服务命名为 order-service

# 配置eureka客户端信息
eureka:
  client:
    service-url:
      # 配置eureka客户端服务order-service的注册地址,与 eureka-server 中暴露地址要保持一致
      defaultZone: http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true # 是否使用 IP 地址注册,默认 false
    # instance-id: order-service  # 实例 id,服务的唯一标识,会自动的找到order-service的ip和端口
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # 如果想在控制页面看到服务地址与端口,可以将 instance-id 这样配置

feign:
  hystrix:
    enabled: true

5、修改订单服务配置文件

由于订单服务中引入的spring-cloud-starter-openfeign依赖中已经集成了feign-hystrix,有了对 Hystrix 的支持,所以不需要额外引入依赖项。如果需要开启 订单服务端的hystrix服务,只需要在订单服务的配置文件配置feign-hystrix 进行激活Hystrix,修改application.yml如下:

server:
  port: 9000
spring:
  application:
    name: order-service # 为当前订单服务命名为 order-service

# 配置eureka客户端信息
eureka:
  client:
    service-url:
      # 配置eureka客户端服务order-service的注册地址,与 eureka-server 中暴露地址要保持一致
      defaultZone: http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true # 是否使用 IP 地址注册,默认 false
    # instance-id: order-service  # 实例 id,服务的唯一标识,会自动的找到order-service的ip和端口
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # 如果想在控制页面看到服务地址与端口,可以将 instance-id 这样配置

feign:
  hystrix:
    enabled: true

6、进行测试

分别访问 http://localhost:9000/order/buy/1 和 http://localhost:9000/order/delete/1 查看浏览器结果如下:


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://blog.csdn.net/qq_41946216/article/details/127371415
相关文章
  • SpringCloud hystrix断路器与局部降级全面介绍

    SpringCloud hystrix断路器与局部降级全面介绍
    服务降级 服务压力剧增的时候,根据当前的业务情况及流量对一些服务和页面有策略的降级,以此缓解服务器的压力,以保证核心任务的进
  • SpringCloud hystrix断路器与全局解耦全面介绍

    SpringCloud hystrix断路器与全局解耦全面介绍
    第七章中在ProductController 和OrderController 中都使用了局部服务降级,但同时也导致两个问题, 通过观察两个局部降级的案例,可以发现: 每
  • SpringBoot自定义错误处理逻辑介绍

    SpringBoot自定义错误处理逻辑介绍
    1. 自定义错误页面 将自定义错误页面放在 templates 的 error 文件夹下,SpringBoot 精确匹配错误信息,使用 4xx.html 或者 5xx.html 页面可以打印错误
  • Java实现手写一个线程池的代码

    Java实现手写一个线程池的代码
    线程池技术想必大家都不陌生把,相信在平时的工作中没有少用,而且这也是面试频率非常高的一个知识点,那么大家知道它的实现原理和
  • Java实现断点续传功能的代码

    Java实现断点续传功能的代码
    题目实现:网络资源的断点续传功能。 二、解题思路 获取要下载的资源网址 显示网络资源的大小 上次读取到的字节位置以及未读取的字节
  • 你可知HashMap为什么是线程不安全的
    HashMap 的线程不安全 HashMap 的线程不安全主要体现在下面两个方面 在 jdk 1.7 中,当并发执行扩容操作时会造成环形链和数据丢失的情况 在
  • ArrayList的动态扩容机制的介绍

    ArrayList的动态扩容机制的介绍
    对于 ArrayList 的动态扩容机制想必大家都听说过,之前的文章中也谈到过,不过由于时间久远,早已忘却。 所以利用这篇文章做做笔记,加
  • JVM基础之字节码的增强技术介绍

    JVM基础之字节码的增强技术介绍
    字节码增强技术 在上文中,着重介绍了字节码的结构,这为我们了解字节码增强技术的实现打下了基础。字节码增强技术就是一类对现有字
  • Java中的字节码增强技术

    Java中的字节码增强技术
    1.字节码增强技术 字节码增强技术就是一类对现有字节码进行修改或者动态生成全新字节码文件的技术。 参考地址 2.常见技术 技术分类 类
  • Redis BloomFilter布隆过滤器原理与实现

    Redis BloomFilter布隆过滤器原理与实现
    Bloom Filter 概念 布隆过滤器(英语:Bloom Filter)是1970年由一个叫布隆的小伙子提出的。它实际上是一个很长的二进制向量和一系列随机映射
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计