Administrator
发布于 2024-01-24 / 2 阅读
0

SpringCloud OpenFeign 使用

OpengFeign 是基于Ribbon,Ribbon 基于restTemplate,OpenFeign只需定义接口,无需具体实现

1.引入依赖

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

2.添加 @EnableFeignClients 在application上

3.定义openFeign 接口类


/**
 * 与 Authority 服务通信的 Feign Client 接口定义
 * */
@FeignClient(
        contextId = "AuthorityFeignClient",//FeignClient 对应微服务 标识
 value = "e-commerce-authority-center",  //目标服务
//        fallback = AuthorityFeignClientFallback.class
        fallbackFactory = AuthorityFeignClientFallbackFactory.class
)
public interface AuthorityFeignClient {

    /**
     * 通过 OpenFeign 访问 Authority 获取 Token
     * */
    @RequestMapping(value = "/ecommerce-authority-center/authority/token",  //请求接口路径
            method = RequestMethod.POST, 
            consumes = "application/json", produces = "application/json") //生产和返回类型,默认情况下不用填写/(原生)
    JwtToken getTokenByFeign(@RequestBody UsernameAndPassword usernameAndPassword);
}

4.接口处直接调用

private final AuthorityFeignClient feignClient;
@PostMapping("/token-by-feign")
    public JwtToken getTokenByFeign(@RequestBody UsernameAndPassword usernameAndPassword) {
        return feignClient.getTokenByFeign(usernameAndPassword);
    }