SpringCloud微服务 之hystrix(四)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012437781/article/details/83714062

前言

前一小节我们学习了如何在FeignClient中开启Hystrix的熔断机制,并实现了fallback方法。本小节我们将学习一下
如何在FeignClient中开启Hystrix的熔断机制并以FallbackFactory地方式返回fallback方法。

  • FallbackFactory VS Fallback
    使用FallbackFactory支持fallback回退可以在回退方法中做自定义扩展,比如对指定的FeignClient指定唯一的回退方法,同时在回退方法中做操作日志记录抑或开启AOP做切面处理、嵌入MQ实时报告异常等等…具体该怎么实现应场景需要。

下面我们就来学习一下在FeignClient中实现FallbackFactory。

案例

  • Eureka Server端编写(参考前例)。
    在这里插入图片描述

  • Eureka Client端服务提供方编写。

    • 项目结构
      在这里插入图片描述

    • CoreCode

      @SpringBootApplication
      @EnableDiscoveryClient
      @EnableFeignClients //开启FeignClient注解
      public class MicroserviceDealBrokerHystrixFallBackFactoryApplication {
      
      	public static void main(String[] args) {
      		SpringApplication.run(MicroserviceDealBrokerHystrixFallBackFactoryApplication.class,
      				args);
      	}
      }
      
      @FeignClient(name = "microservice-deal-cloud",fallbackFactory = FeignClientFallbackFactory.class)
      public interface FeignClientUserInterface {
      
      	//第一个坑:使用Feign的时候,如果参数中带有@PathVariable形式的参数,则要用value=""标明对应的参数,否则会抛出IllegalStateException异常
      	@GetMapping("/deal/{id}")
      	public Deal findById(@PathVariable(value="id") Long id);
      }
      
      
      /**
       * FeignClientUserInterface的fallbackFactory类,该类需实现FallbackFactory接口,并覆写create方法 The
       * fallback factory must produce instances of fallback classes that implement
       * the interface annotated by {@link FeignClient}.
       */
      @Component
      public class FeignClientFallbackFactory implements FallbackFactory<FeignClientUserInterface> {
      	private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientFallbackFactory.class);
      
      	@Override
      	public FeignClientUserInterface create(Throwable cause) {
      		return new FeignClientUserInterface() {
      			@Override
      			public Deal findById(Long id) {
      				// 日志最好放在各个fallback方法中,而不要直接放在create方法中。
      				// 否则在引用启动时,就会打印该日志。
      				FeignClientFallbackFactory.LOGGER.info("fallback; reason was:", cause);
      				Deal deal = new Deal();
      				deal.setId(id.intValue());
      				deal.setName("Dustyone");
      				return deal;
      			}
      		};
      	}
      }
      
      /**
       * FeignClientUserInterface的fallbackFactory类,该类需实现FallbackFactory接口,并覆写create方法 The
       * fallback factory must produce instances of fallback classes that implement
       * the interface annotated by {@link FeignClient}.
       */
      @Component
      public class FeignClientFallbackFactory implements FallbackFactory<FeignClientUserInterface> {
      	private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientFallbackFactory.class);
      
      	@Override
      	public FeignClientUserInterface create(Throwable cause) {
      		return new FeignClientUserInterface() {
      			@Override
      			public Deal findById(Long id) {
      				// 日志最好放在各个fallback方法中,而不要直接放在create方法中。
      				// 否则在引用启动时,就会打印该日志。
      				FeignClientFallbackFactory.LOGGER.info("fallback; reason was:", cause);
      				Deal deal = new Deal();
      				deal.setId(id.intValue());
      				deal.setName("Dustyone");
      				return deal;
      			}
      		};
      	}
      }
      
      server:
        port: 8082
      spring:
        application:
          name: microservice-deal-broker-cloud-hystrix-fallback-factory
      eureka:
        client:
          serviceUrl:
            defaultZone: http://localhost:8080/eureka/
        instance:
          prefer-ip-address: true
      
      #声明Feign中的Hystrix
      # 说明:请务必注意,从Spring Cloud Dalston开始,Feign默认是不开启Hystrix的。
      # 因此,如使用Dalston请务必额外设置属性:feign.hystrix.enabled=true,否则断路器不会生效。
      # 而,Spring Cloud Angel/Brixton/Camden中,Feign默认都是开启Hystrix的。无需设置该属性。
      feign:
        hystrix:
          enabled: true
      #使用Feign时必须添加以下两项配置
      ribbon:
        eureka:
          enabled: true
      
      #设置feign的hystrix响应超时时间(必须)
      hystrix:
        command:
            default:
              execution:
                isolation:
                  thread:
                    timeoutInMilliseconds: 5000
      
      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      	<modelVersion>4.0.0</modelVersion>
      
      	<artifactId>microservice-deal-broker-cloud-hystrix-fallback-factory</artifactId>
      	<packaging>jar</packaging>
      
      	<name>microservice-deal-broker-cloud-hystrix-fallback-factory</name>
      	<description>Demo project for Spring Boot</description>
      
      	<parent>
      		<groupId>com.example</groupId>
      		<artifactId>microservice-deal-parent</artifactId>
      		<version>0.0.1-SNAPSHOT</version>
      	</parent>
      
      	<dependencies>
      		<!-- Eureka -->
      		<dependency>
      			<groupId>org.springframework.cloud</groupId>
      			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      		</dependency>
      
      		<!-- Feignf -->
      		<dependency>
      			<groupId>org.springframework.cloud</groupId>
      			<artifactId>spring-cloud-starter-openfeign</artifactId>
      		</dependency>
      
      		<!-- springCloud Hystrix依赖 -->
      		<dependency>
      			<groupId>org.springframework.cloud</groupId>
      			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
      		</dependency>
      
      	</dependencies>
      
      </project>
      
      
  • Eureka Client端服务提消费编写(单实例) (参考前例)。

  • 访问:http://localhost:8082/deal/2
    在这里插入图片描述

  • 手动将服务提供者shutdown:
    在这里插入图片描述

  • 访问:http://localhost:8082/deal/2
    在这里插入图片描述

  • 服务消费者后台日志:
    在这里插入图片描述

此时便实现了FeignClient中使用fallbackFactory实现fallback回退。

小结

  • FallbackFactory较普通的Fallback优势在于FallbackFactory支持更过的扩展功能如各种AOP实现机制与Logger捕捉等等。
  • 在FeignClientInterface类中的@FeignClient注解中加入fallbackFactory = FeignClientFallbackFactory.class节点以声明回退fallbackFactory。
  • 更过需要注意的细节参考前一小节,因为本小节是完全在前一小节基础之上的完善的。
  • 使用到的案例:microservice-deal-eureka、microservice-deal-cloud、microservice-deal-broker-cloud-hystrix-fallback-factory

猜你喜欢

转载自blog.csdn.net/u012437781/article/details/83714062