4、openFeign契约配置

本文介绍了如何在SpringCloud中从早期Feign版本升级到OpenFeign,通过全局或局部配置,保持原生Feign注解的同时支持SpringMVC。重点讲解了契约配置的作用以及两种配置方法:一是通过@Configuration类,二是通过application.yml文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Cloud 在 Feign 的基础上做了扩展,使用 Spring MVC 的注解来完成Feign的功能。原生的 Feign 是不支持 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的注解方式来定义客户端也是可以的,通过配置契约来改变这个配置,Spring Cloud 中默认的是 SpringMvcContract。

Spring Cloud 1 早期版本就是用的原生Fegin. 随着netflix的停更替换成了Open feign

为什么需要契约配置?
答:比方说,以前springcloud1.0的早期版本它就是用的原生的feign,随着netflix的停更才替换成了Open feign,Open feign在 Feign 的基础上做了扩展,使用 Spring MVC 的注解来完成Feign的功能,从而降低了学习的成本。假如说我有项目就是用的spring cloud 1.0早期的版本,我现在想做版本的升级,想升级为比较新的版本,我想用openFeign;但是我一升级的话,项目中的feign的接口当中的原生注解是不是都得改掉,在小的代码变更都会引起bug的出现。我们尽量能少改代码就改代码。我们用契约配置就可以符合我们的功能。我们既能升级我的spring cloud的版本,我又可以保留我原生的feign注解,从而降低修改代码产生的风险。

全局配置

在order-feign模板修改

第一步:修改FeignConfig

package com.example.order.config;

import feign.Contract;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 全局配置:当使用@Configuration会将配置作用所有的服务提供方
 * 局部配置:如果只想针对某一个服务进行配置,就不要加@Configuration
 */
@Configuration
public class FeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }

    /**
     * 修改契约配置,支持Feign原生的注解
     * @return
     */
    @Bean
    public Contract feignContract(){
        return new Contract.Default();
    }
}

第二步:修改所有Feign服务

package com.example.order.feign;

import com.example.order.config.FeignConfig;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "stock-service",path = "/stock",configuration = FeignConfig.class)
public interface StockFeignService {

    /**
     * 声明需要调用的rest接口对应的方法
     * 保持跟被调用方的controller一致,去掉方法体和public
     */
    @RequestLine("GET /reduck")    //相当于@RequestMapping("/reduck")
    String reduck();


    /**
     * @RestController
     * @RequestMapping("/stock")
     * public class StockController {
     *
     *     @Value("${server.port}")
     *     private String port;
     *
     *     @RequestMapping("/reduck")
     *     public String reduck(){
     *         System.out.println("扣减库存");
     *         return "扣减库存" + port;
     *     }
     * }
     */
}

package com.example.order.feign;

import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "product-service",path = "/product")
public interface ProductFeignService {

    /**
     * 注意:在springmvc中@PathVariable不给value属性赋值,默认为变量名对应@RequestMapping
     * 但feign必须需要指定value,否则会报“PathVariable annotation was empty on param 0."错误
     */
    @RequestLine("GET /{id}") //相当于@RequestMapping({id})
    String get(@Param("id") Integer id); //相当于PathVariable("id")
}

第三步:重启order-openfeign

重启order-openfeign,访问http://localhost:8086/order/add发现正常访问ok

局部配置

第一种:通过配置类

第一步:修改FeignConfig

package com.example.order.config;

import feign.Contract;
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * 全局配置:当使用@Configuration会将配置作用所有的服务提供方
 * 局部配置:如果只想针对某一个服务进行配置,就不要加@Configuration
 */
//@Configuration
public class FeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }

    /**
     * 修改契约配置,支持Feign原生的注解
     * @return
     */
    @Bean
    public Contract feignContract(){
        return new Contract.Default();
    }
}

第二步:修改StockFeignService和ProductFeignService

package com.example.order.feign;

import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "product-service",path = "/product")
public interface ProductFeignService {

    /**
     * 注意:在springmvc中@PathVariable不给value属性赋值,默认为变量名对应@RequestMapping
     * 但feign必须需要指定value,否则会报“PathVariable annotation was empty on param 0."错误
     */
    @RequestMapping("/{id}") //@RequestLine相当于@RequestMapping({id})
    String get(@PathVariable("id") Integer id); //@Param相当于@PathVariable("id")
}

package com.example.order.feign;

import com.example.order.config.FeignConfig;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "stock-service",path = "/stock",configuration = FeignConfig.class)
public interface StockFeignService {

    /**
     * 声明需要调用的rest接口对应的方法
     * 保持跟被调用方的controller一致,去掉方法体和public
     */
    @RequestLine("GET /reduck")    //相当于@RequestMapping("/reduck")
    String reduck();

}

第三步:重启order-openfeign

重启order-openfeign,访问http://localhost:8086/order/add发现正常访问ok

第二种:通过配置文件

第一步:修改FeignConfig

package com.example.order.config;

import feign.Contract;
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * 全局配置:当使用@Configuration会将配置作用所有的服务提供方
 * 局部配置:如果只想针对某一个服务进行配置,就不要加@Configuration
 */
//@Configuration
public class FeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }

    /**
     * 修改契约配置,支持Feign原生的注解
     * @return
     */
//    @Bean
//    public Contract feignContract(){
//        return new Contract.Default();
//    }
}

第二步:修改application.yml

server:
  port: 8086
#应用名称(nacos会将该名称当做服务名称)
spring:
  application:
    name: order-service
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public
  # 因为feign调试日志是debug级别输出,springboot默认的日志级别是info,所以feign的debug日志级别就不会输出
  # logging.level=debug这样配置是对所有的日志级别进行配置
  # 该场景只需要对feign接口进行debug配置,所以是这样配置logging.level.com.example.order.feign=debug
logging:
  level:
    com.example.order.feign: debug
feign:
  client:
    config:
      # 提供方的服务名
      product-service:
        #请求日志级别
        loggerLevel: BASIC
        contract: feign.Contract.Default #设置为默认的契约(还原成原生注解)

第三步:修改StockFeignService和ProductFeignService

package com.example.order.feign;

import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "product-service",path = "/product")
public interface ProductFeignService {

    /**
     * 注意:在springmvc中@PathVariable不给value属性赋值,默认为变量名对应@RequestMapping
     * 但feign必须需要指定value,否则会报“PathVariable annotation was empty on param 0."错误
     */
    @RequestLine("GET /{id}") //@RequestLine相当于@RequestMapping({id})
    String get(@Param("id") Integer id); //@Param相当于@PathVariable("id")
}

package com.example.order.feign;

import com.example.order.config.FeignConfig;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * name指定调用rest接口欧所对应的服务名,被调用服务的应用名
 * path指定调用rest接口所在的StockController指定的@RequestMapping
 */
@FeignClient(name = "stock-service",path = "/stock",configuration = FeignConfig.class)
public interface StockFeignService {

    /**
     * 声明需要调用的rest接口对应的方法
     * 保持跟被调用方的controller一致,去掉方法体和public
     */
    @RequestMapping("/reduck")    //相当于@RequestMapping("/reduck")
    String reduck();


    /**
     * @RestController
     * @RequestMapping("/stock")
     * public class StockController {
     *
     *     @Value("${server.port}")
     *     private String port;
     *
     *     @RequestMapping("/reduck")
     *     public String reduck(){
     *         System.out.println("扣减库存");
     *         return "扣减库存" + port;
     *     }
     * }
     */
}

第四步:重启order-openfeign

重启order-openfeign,访问http://localhost:8086/order/add发现正常访问ok
### OpenFeign 4.0 新特性 OpenFeign作为声明式的Web服务客户端,简化了HTTP API调用过程。对于版本4.0而言,虽然具体提及此版本的新特性的直接资料较少见,但从相关技术演进和发展趋势来看,可以推测一些改进方向[^2]。 #### 日志级别增强 在日志管理方面,提供了更细致的日志控制选项。开发者能够通过设置不同的日志级别来获取所需的信息量: - `NONE`:关闭所有日志输出。 - `BASIC`:记录基本的请求方法、URL及响应状态码和执行时间。 - `HEADERS`:除了上述基本信息外,还会打印出请求与响应头部信息。 - `FULL`:最详细的模式,会记录完整的请求和响应细节,包括但不限于头信息、主体内容等。 这些级别的设定有助于调试期间更好地理解API交互情况,并可根据实际需求调整日志粒度以优化性能表现。 ```yaml logging: level: com.example.feignclient: DEBUG ``` 以上配置可使指定路径下的Feign Client启用DEBUG级别的日志输出,从而方便观察其工作流程。 --- ### 使用指南 为了有效利用OpenFeign的功能,在项目集成过程中需要注意以下几个要点: 1. **引入依赖** 需要在项目的构建文件(如Maven的pom.xml或Gradle的build.gradle)中加入必要的库依赖项,确保应用程序能识别并加载OpenFeign组件。 2. **定义接口** 创建一个Java接口用于描述目标RESTful API的服务契约,其中每个方法对应一次远程调用操作。使用注解方式标注参数映射关系和服务地址等信息。 3. **启动类配置** 在Spring Boot应用的主要入口处添加@EnableFeignClients注解,激活对Feign Clients的支持机制。 4. **自定义配置(可选)** 如果希望进一步定制化行为,则可以通过编写特定于某个Feign Client实例的Bean来进行属性覆盖或是重写默认的行为逻辑。 ```java @FeignClient(name="exampleService", url="${service.url}") public interface ExampleClient { @GetMapping("/api/resource") ResponseEntity<Resource> getResource(); } ``` 这段代码展示了如何创建一个简单的Feign Client接口,用来访问名为`exampleService`的服务资源。 --- ### 更新日志 关于具体的更新日志条目,通常这类信息会被维护在一个官方文档页面或者是GitHub仓库中的CHANGELOG.md文件里。由于当前提供的参考资料并未涉及确切的变更列表,建议查阅开源社区发布的正式公告或者查看源码历史提交记录来获得最权威的第一手消息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值