feignclient,参数传body,应该怎么写

在Feign Client中传递请求体(body)参数,主要有以下几种方式:

1. 基本使用方式

1.1 使用 @RequestBody注解

复制代码
@FeignClient(name = "service-name", url = "${service.url}")
public interface MyFeignClient {
    
    @PostMapping("/api/user")
    UserDTO createUser(@RequestBody UserRequest request);
}

1.2 完整示例

复制代码
// 请求体对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRequest {
    private String username;
    private String email;
    private Integer age;
    private List<String> roles;
}

// 响应体对象
@Data
public class UserDTO {
    private Long id;
    private String username;
    private String email;
}

// Feign Client
@FeignClient(name = "user-service", url = "http://localhost:8080")
public interface UserFeignClient {
    
    @PostMapping("/users")
    UserDTO createUser(@RequestBody UserRequest request);
    
    @PutMapping("/users/{id}")
    UserDTO updateUser(@PathVariable("id") Long id, @RequestBody UserRequest request);
    
    @PatchMapping("/users/{id}")
    UserDTO partialUpdateUser(@PathVariable("id") Long id, @RequestBody Map<String, Object> updates);
}

2. 多种参数类型传递

2.1 Map类型参数

复制代码
@FeignClient(name = "dynamic-service")
public interface DynamicFeignClient {
    
    @PostMapping("/api/data")
    String postData(@RequestBody Map<String, Object> data);
    
    @PostMapping("/api/search")
    SearchResult search(@RequestBody SearchCriteria criteria, 
                       @RequestParam("page") int page,
                       @RequestParam("size") int size);
}

2.2 List类型参数

复制代码
@FeignClient(name = "batch-service")
public interface BatchFeignClient {
    
    @PostMapping("/api/batch")
    BatchResult processBatch(@RequestBody List<BatchItem> items);
}

3. 复杂请求示例

3.1 包含请求头的复杂请求

复制代码
@FeignClient(name = "auth-service")
public interface AuthFeignClient {
    
    @PostMapping(value = "/oauth/token", 
                 consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    TokenResponse getToken(@RequestBody MultiValueMap<String, String> formData,
                          @RequestHeader("Authorization") String authorization);
}

3.2 文件上传

复制代码
@FeignClient(name = "file-service")
public interface FileFeignClient {
    
    @PostMapping(value = "/upload", 
                 consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    UploadResult uploadFile(@RequestPart("file") MultipartFile file,
                           @RequestPart("metadata") @RequestBody FileMetadata metadata);
}

4. 配置类配置

4.1 自定义配置

复制代码
@Configuration
public class FeignConfig {
    
    @Bean
    public Encoder feignEncoder() {
        ObjectFactory<HttpMessageConverters> messageConverters = () -> 
            new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
        return new SpringEncoder(messageConverters);
    }
    
    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(messageConverters()));
    }
    
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

5. 使用示例

复制代码
@Service
public class UserService {
    
    @Autowired
    private UserFeignClient userFeignClient;
    
    public UserDTO createNewUser(String username, String email) {
        UserRequest request = new UserRequest();
        request.setUsername(username);
        request.setEmail(email);
        request.setAge(25);
        request.setRoles(Arrays.asList("USER", "MEMBER"));
        
        return userFeignClient.createUser(request);
    }
    
    public String postDynamicData() {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "test");
        data.put("value", 123);
        data.put("items", Arrays.asList("item1", "item2"));
        
        return userFeignClient.postData(data);
    }
}

6. 注意事项

  1. JSON序列化:默认使用Jackson,确保对象有正确的getter/setter

  2. Content-Type :默认是application/json,可通过consumes属性修改

  3. 空值处理:默认不序列化null值,可通过配置修改

  4. 编码器/解码器:可自定义处理特定类型

  5. 异常处理:建议使用ErrorDecoder处理异常

7. 常见问题解决

7.1 日期格式处理

复制代码
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;

7.2 自定义序列化

复制代码
@FeignClient(name = "service", configuration = CustomFeignConfig.class)
public interface CustomClient {
    // ...
}

7.3 启用GZIP压缩

复制代码
feign:
  compression:
    request:
      enabled: true
    response:
      enabled: true

以上是在Feign Client中传递body参数的完整写法,根据实际需求选择合适的方式。

相关推荐
the3clipse20 小时前
MPC-HC 下载安装与最佳配置教程:免费开源、轻量无广告、支持 4K 硬解的 Windows 播放器
windows·播放器·安装教程·硬件加速·mpc-hc·字幕设置·lav filters
独隅20 小时前
WebStorm Windows 版 React / Next.js 实战替换指南
javascript·windows·webstorm
陈工大模型20 小时前
2026年11月最新免费解压软件横评:7-Zip 、 Win解压缩名列前茅
windows·软件工程·7-zip·压缩软件
中二骚年2 天前
Windows 安全中心 / 防火墙故障,calc和Microsoft Store,终端(管理员)无法正常打开。 原因 + 修复方案
windows·安全·microsoft
万联WANFLOW2 天前
CVE-2026-98432 等漏洞自查:AI 查出的 Linux、Windows 漏洞,运维怎么确认受不受影响
linux·运维·windows·网络安全
AlanAshley2 天前
Windows 中导致延迟的软硬件及协议比重
windows
yuezhilangniao2 天前
win10中文 以及 PowerShell 开发日常
windows·powershell
共享家95273 天前
408 操作系统第一章
服务器·数据库·windows
Sakura_j_h_3 天前
GitHub Actions 打包 Windows exe:中文编码与产物上传
windows·ci/cd·打包发布·github·pyinstaller·github actions
xixiaoyunya3 天前
搭一个浏览器即用的二进制文件分发点:目录规范与权限边界实践
网络·windows