Spring Cloud 中OpenFeign的使用(二)

在OpenFeign中主要的注解就是@FeignClient,从@FeignClient注解源码来看其被@Target({ElementType.TYPE})注解修饰,说明其注解的作用目标接口、类、枚举、注解上,
声明接口之后,在代码中通过@Resource注入之后即可使用,从接口上可以看到@FeignClient注解的常用属性。

name/value:从FeignClient注解属性来看name属性别名是value,value属性别名是name,两个属性参数作用是一样的,都是指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现。

实例:通过name或value指定服务名,根据服务名调用getGoodsList服务接口。

@FeignClient(name = "goods-service")
public interface GoodsService
{
    @GetMapping("/goods/list")
    String getGoodsList();
}

或者

@FeignClient(value = "goods-service")
public interface GoodsService
{
    @GetMapping("/goods/list")
    String getGoodsList();
}

 url:属性一般用于调试程序,允许我们手动指定@FeignClient调用的地址。

实例:手动指定@FeignClient服务调用的地址

@FeignClient(value = "goods-service", url="http://127.0.0.1:7001")
public interface GoodsService
{
    @GetMapping("/goods/list")
    String getGoodsList();
}

 fallbackFactory:工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码。

实例:fallbackFactory 显示记录服务熔断异常信息

@FeignClient(value = "goods-service",  fallbackFactory = GoodsServiceFallbackFactory.class)
public interface GoodsService
{
    @GetMapping("/goods/list")
    String getGoodsList();
}

需要实例化FallbackFactory的实现类,重写create()方法

@Component
public class GoodsServiceFallbackFactory implements FallbackFactory<GoodsService>
{
    @Override
    public GoodsService create(Throwable throwable)
    {
        return new GoodsService()
        {
            @Override
            public String getGoodsList()
            {
                return throwable.getMessage();
            }
        };
    }
}

 fallback:定义容错的处理类,当调用远程接口失败或超时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口,fallback 和 FallbackFactory 同时使用,fallback优先级要高于FallbackFactory。

实例:fallback 显示记录服务熔断信息

@FeignClient(value = "goods-service",  fallback = GoodsServiceFallback.class)
public interface GoodsService
{
    @GetMapping("/goods/list")
    String getGoodsList();
}
@Component
public class GoodsServiceFallback implements GoodsService
{
    @Override
    public String getGoodsList() {
       return "服务熔断";
    }
}

path:定义当前FeignClient的服务统一前缀,这样方便在该FeignClient中的@RequestMapping中书写value值
实例:定义一个FeignClient,定义服务前缀为"/goods/list"

@FeignClient(value = "goods-service", path="/goods")
public interface GoodsService
{
    @GetMapping("list")
    String getGoodsList();
}
原文地址:https://www.cnblogs.com/huxiaoguang/p/14742544.html