美文网首页
open feign 使用备忘

open feign 使用备忘

作者: JohnYuCN | 来源:发表于2021-07-08 15:51 被阅读0次

    一、原理

    1. 声明式Rest Client
    2. 是对Ribbon的封装(间接对httpclient或okhttp的封装)
    3. 采用动态代理机制,针对接口直接生成远程代理对象
    4. 同时支持:Feign annotations and JAX-RS annotations(或SpringMVC annotations)
    5. 支持较简单的熔断和降级的规则

    二、开发过程:

    1. pom.xml
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
    1. 主启动类:
    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    public class OrderApp {
        public static void main(String[] args) {
          ...
    
    1. 配置服务接口,用以生成代理对象,并向Controller进行注入:
      service
    @Component
    @FeignClient(value = "payment") //payment为注册在Eureka中的服务名称
    public interface PaymentService {
        //此处也可以使用javax.rs.Path进行注解
        @RequestMapping(value = "/payments/{id}",method = RequestMethod.GET)
        CommonResult<Payment> loadPayment(@PathVariable(value = "id") int id);
    }
    

    controller

    //controller的代码片段
        @Resource
        private PaymentService paymentService;
        @GetMapping("/payments/{id}")
        public CommonResult<Payment> loadPaymentWithFeign(@PathVariable(value = "id") int id){
            return paymentService.loadPayment(id);
        }
    

    三、负载均衡规则:

    由于其是对Ribbon的的封装,所以原有的Ribbon规则的配置方法,仍然适用,如:

    //配置多个规则的方式
    @RibbonClients(
                value = {
                        @RibbonClient(value = "payment",configuration = MyRuleConf.class)
                        ,@RibbonClient(value = "other",configuration = YourRuleConf.class)
                }
            )
    

    此时,对payment服务的规则,将由MyRuleConf.java确定,详见的我的简书:Ribbon使用备忘

    四、配置open feign的一般方法:

    application.yml
    全局配置:

    feign:
        client:
            config:
                default:
                    connectTimeout: 5000
                    readTimeout: 5000
                    loggerLevel: basic
    

    针对feignName(payment服务名)的配置:

    feign:
        client:
            config:
                payment:
                    connectTimeout: 5000
                    readTimeout: 5000
    

    --- 参考: https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/#spring-cloud-feign
    --- 参考:
    https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/appendix.html

    相关文章

      网友评论

          本文标题:open feign 使用备忘

          本文链接:https://www.haomeiwen.com/subject/vyhtpltx.html