Spring Cloud 07 -- Feign 中使用断路器

2019-08-12  本文已影响0人  半碗鱼汤

一、说明

之前我们使用 Feign 实现 client01 调用 client02 的接口,但是如果 client02 在使用过程中崩溃了,那么 client01 还去调用其接口就会出错。这时候,我们引入断路器 Hystrix ,使调用已经崩溃的 client02 的接口时,返回人性化提示给用户。接下来我们将改造 client01 工程。

二、修改 client01 的配置文件

Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:

#为了打开 feign 的 hystrix 功能
feign:
  hystrix:
    enabled: true

完整配置文件如下:

server:
  port: 8763

spring:
  application:
    name: client01

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  #为了在服务注册中心里显示实际的 IP 地址,需添加下面的配置
  instance:
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    prefer-ip-address: true

#为了打开 feign 的 hystrix 功能
feign:
  hystrix:
    enabled: true

三、添加断路器处理类

在 service 包下新建一个 impl 包,里面新建一个 UseOtherApiServiceImpl 类实现 IUseOtherApiService 接口。

import com.dhsg.sc.client01.service.IUseOtherApiService;
import org.springframework.stereotype.Service;

/**
 * 断路器
 */

@Service
public class UseOtherApiServiceImpl implements IUseOtherApiService {

    /**
     * 在 client02 出现故障的时候,调用 client01 的 /forclient01 接口
     *
     * @return 错误提示
     */
    @Override
    public String getClient02Name() {
        return "client02 已经崩溃,无法访问!";
    }

}

四、在 IUseOtherApiService 接口上的注解 @FeignClient 添加 fallback

@FeignClient(value = "client02",fallback = UseOtherApiServiceImpl.class)

完整代码如下

import com.dhsg.sc.client01.service.impl.UseOtherApiServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 添加注解 @FeignClient(value = "client02") 的作用是能够访问服务提供者 client02 的接口
 * 添加 fallback 是为了添加断路器
 */

@Service
@FeignClient(value = "client02",fallback = UseOtherApiServiceImpl.class)
public interface IUseOtherApiService {

    /**
     * 调用 client01 的 /forclient01 接口
     *
     * @return 获取到 client01 的端口和服务名并返回
     */
    @RequestMapping(value = "/forclient01", method = RequestMethod.GET)
    public String getClient02Name();

}

五、访问 http://localhost:8763/getclient02name

通过 client01 调用 client02 的接口
上一篇 下一篇

猜你喜欢

热点阅读