future.png
珠玑随笔

联系:

future.png

版权 © 2022 by Hsu

技术: Gatsby

样式: Bulma

许可: CC BY NC SA 4.0

Spring Cloud 服务通信 OpenFeign

2022年01月16日

Hsu

1分钟

背景

Spring Cloud OpenFeign 是一个 HTTP 客户端, 用来发送请求获取数据.

Spring Cloud Gateway 需要连接 Eurake 或其他服务发现组件读取路由表.

安装

引入以下依赖.

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

启动类添加 @EnableFeignClients

@SpringBootApplication
@EnableFeignClients
public class ConversionServiceApplication {

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

使用

定义一个接口.


//@FeignClient(name="currency-exchange", url="localhost:8000") // 普通请求
@FeignClient(name = "exchange-service") // 负载均衡
public interface ConversionExchangeProxy {

  @GetMapping("/exchange/get")
  public String retrieveExchangeValue();

}

使用它获取数据.


@RestController
public class ConversionController {

  @Autowired
  private ConversionExchangeProxy proxy;

  @GetMapping("/exchange")
  public String exchangeValue() {
    return proxy.retrieveExchangeValue();
  }
}

错误拦截

https://stackoverflow.com/questions/55020389/spring-feign-client-exception-handling

https://www.javacodemonk.com/feign-exception-handling-spring-cloud-20d17f69

https://www.baeldung.com/spring-cloud-openfeign

参考

https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/