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参数的完整写法,根据实际需求选择合适的方式。

相关推荐
埃博拉酱4 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
tryCbest4 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅4 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技4 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~4 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
一个假的前端男4 天前
[特殊字符] Flutter 安装完整指南 Windows—— 2026最新版
windows·flutter
倚肆5 天前
在 Windows Docker 中安装并配置 Nginx (映射 Windows 端口与路径)
windows·nginx·docker
破无差5 天前
拯救你的C盘
windows