Netflix Hystrix @DefaultProperties 全局回退

上面章节介绍了 Hystrix 的基础用法,本文将介绍通过 @DefaultProperties 注解配置 Hystrix 全局默认回调方法。

@DefaultProperties 注解

该注解用于为 Hystrix 命令指定默认参数,例如:defaultFallback = "defaultFallback"。如果我们需要为某个特定方法指定参数,可以使用 @HystrixCommand 注解。

  • groupKey:默认情况下指定的每个 Hystrix 命令使用默认组密钥,除非命令显式指定组密钥。默认为空字符串

  • threadPoolKey:默认情况下指定的每个 Hystrix 命令使用默认线程池密钥,除非命令显式指定了线程池密钥。默认为空字符串

  • commandProperties:将用于为每个 Hystrix 命令的命令属性指定默认属性,除非在 @HystrixCommand 中显式指定命令属性。

  • threadPoolProperties:将用于为每个 Hystrix 命令的线程池属性指定默认值,除非在 @HystrixCommand 中显式指定线程池属性。

  • ignoreExceptions:定义应该被忽略的异常。如果 raiseHystrixExceptions 包含 RUNTIME_EXCEPTION,则这些可以被包装在 HystrixRuntimeException 中。

  • raiseHystrixExceptions:当包含 RUNTIME_EXCEPTION 时,任何未被忽略的异常都会被包装在 HystrixRuntimeException 中。

  • defaultFallback:为给定类中的每个命令指定默认回退方法。类中的每个命令都应该有一个与默认回退方法返回类型兼容的返回类型。注意:默认回退方法不能有参数。

提供 Eureka Server 和  User 服务

在前面章节介绍了 Eureka Server 和 user 服务的搭建,详细信息参考 “Hystrix入门实例” 章节。

Hystrix 实例

pom.xml

为了使用 Hystrix 组件,需要在 maven 中添加如下依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

application.yml

在该配置文件中配置 Eureka Server 注册中信息地址,服务端口、名称信息。配置如下:

server:
  port: 8080
spring:
  application:
    name: demo
# 服务地址
eureka:
  instance:
    hostname: localhost
    # 心跳间隔5s,默认30s。每一个服务配置后,心跳间隔和心跳超时时间会被保存在server端,
    # 不同服务的心跳频率可能不同,server 端会根据保存的配置来分别探活
    lease-renewal-interval-in-seconds: 5
    # 心跳超时时间10s,默认90s。从client端最后一次发出心跳后,达到这个时间没有再次发出
    # 心跳,表示服务不可用,将它的实例从注册中心移除
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      # 注册中心路径,表示我们向这个注册中心注册服务,如果向多个注册中心注册,用“,”进行分隔
      defaultZone: http://localhost:8077/eureka

RestTemplateConfig.java

使用 @Configuration 配置类配置 RestTemplate,并且在 RestTemplate 上面添加 @LoadBalanced 注解。开启负载均衡功能,配置如下:

package com.hxstrive.springcloud.hystrix;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    // 配置一个 RestTemplate
    @Bean
    // 添加该注解后,可以使得 RestTemplate 拥有负载均衡能力
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

DemoService.java

在类中注入 RestTemplate 实例,使用 RestTemplate 实例去调用前面提供的 User 服务。代码如下:

package com.hxstrive.springcloud.hystrix;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class DemoService {

    @Autowired
    private RestTemplate restTemplate;

    public String getInfo() {
        System.out.println("restTemplate=" + restTemplate);
        // 如果你要实现负载均衡,调用地址不能写具体主机地址
        // 需要将主机地址替换成对于服务的服务名,即 spring.application.name 指定的值
        // 你也可以到 Eureka server 中去查看
        String url = "http://USER/info";
        ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class);
        if(resp.getStatusCode().is2xxSuccessful()) {
            return resp.getStatusCode().value() + " :: " + resp.getBody();
        } else {
            return resp.getStatusCode().value() + " :: " + resp.getBody();
        }
    }

}

HystrixDemo2Application.java

客户端代码,在类上面添加 @DefaultProperties(defaultFallback = "defaultFallback" ) 注解,配置默认回退方法。代码如下:

package com.hxstrive.springcloud.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
// 启用断路器
@EnableCircuitBreaker
// 配置全局Hystrix
@DefaultProperties(defaultFallback = "defaultFallback" )
public class HystrixDemo2Application {

    @Autowired
    private DemoService demoService;

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

    @GetMapping({"/"})
    @HystrixCommand
    public String index() {
        return demoService.getInfo();
    }

    /**
     * 全局回调方法【回退方法】
     */
    private String defaultFallback() {
        return "很抱歉,网络拥挤!";
    }

}

运行方式

第一步:启动 Eureka Server 服务;

第二步:启动 User 服务,然后通过浏览器查看 User 服务是否已经注册到 Eureka Server 中;

第三步:启动 Hystrix 实例,通过浏览器访问实例,访问正常。如果我们将 User 服务暂停,再次访问 Hystrix 实例,返回信息为回退方法返回的值。

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号