springCloud-29 feign 调用hystrix 实现服务熔断

2022-08-12 08:57:18
SpringCloud Fegin默认已为Feign整合了hystrix,所以添加Feign依赖后就不用在添加hystrix,那么怎么才能让Feign的熔断机制生效呢,只要按以下步骤开发:

一,添加feign依赖

 <!--springCloud整合feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

二,配置application.yml 在Feign中开启hystrix

        在Feign中已经内置了hystrix,但是默认是关闭的需要在工程的application.yml中开启对hystrix的支持
server:
  port: 9013
  tomcat:
    max-threads: 10 # 设置线程数为最大10个
spring:
  application:
    name: service-order-hystrix
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springclouddemo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: root
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9003/eureka/,http://localhost:9004/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port} #向注册中心中展示注册服务id
    lease-expiration-duration-in-seconds: 10 #eureka client 发送心跳给server端后,续约到期时间(默认为90秒)。
    lease-renewal-interval-in-seconds: 5 # 发送心跳续约间隔(每一个心跳的间隔)
#修改ribbon的负载均衡策略 服务名-ribbon-NFLoadBalancer
service-product:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
    ConnectTimeout: 250 # Ribbon的连接超时时间
    ReadTimeout: 3000 # Ribbon的数据读取超时时间
    OkToRetryOnAllOperations: true # 是否对所有操作都进行重试
    MaxAutoRetriesNextServer: 1 # 切换实例的重试次数
    MaxAutoRetries: 1 # 对当前实例的重试次数

feign:
  client:
    config:
      service-product: # 服务提供者的服务名称
            loggerLevel: FULL
  hystrix:
    enabled: true
logging:
  level:
    com.zjk.order.feign.productFeignHttpClient: debug #feign的自定义接口

三,修改productFeignClient添加hystrix熔断

//指定需要调用的服务名称
@FeignClient(name = "service-product",fallback = ProductFeignClientCallBack.class)
public interface productFeignHttpClient {

    //调用的请求路径
    @RequestMapping(value = "/product/{Id}",method = RequestMethod.GET)
    public TbProduct findById(@PathVariable("Id") Long Id);
}

四,配置FeignClient接口的实现类

@Component
public class ProductFeignClientCallBack implements productFeignHttpClient {

    @Override
    public TbProduct findById(Long Id) {
        TbProduct tbProduct = new TbProduct();
        tbProduct.setProductName("服务降级");
        return tbProduct;
    }
}

@FeignClient注解中以fallback声明降级方法

  • 作者:vegetari
  • 原文链接:https://blog.csdn.net/qq_41169544/article/details/122591751
    更新时间:2022-08-12 08:57:18