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

相关推荐
比奇堡鱼贩1 天前
python第二次作业--函数
linux·运维·windows
小白郭莫搞科技1 天前
鸿蒙跨端框架Flutter学习:ListView卡片样式详解
linux·服务器·windows
九皇叔叔1 天前
【05】SpringBoot3 MybatisPlus 添加(Mapper)
windows
水饺编程1 天前
第4章,[标签 Win32] :系统字体与字符大小
c语言·c++·windows·visual studio
i建模1 天前
在Windows系统上通过SSH访问远程AWS主机
windows·ssh·aws
Hx_Ma161 天前
List 转二维 List
数据结构·windows·list
软件资深者1 天前
植物大战僵尸1经典版(小游戏)+超强辅助工具 自动收取阳光
windows·游戏程序·windows11
雄狮少年1 天前
AI Agent Workflow基类及实现类,快速实现一个react agent,可直接运行
人工智能·windows·react.js
Kazefuku1 天前
VS Code 和Visual Studio:简单易懂的区别
ide·windows·visual studio
Asssshzy1 天前
校园网断网无法远程电脑的解决方案
windows·计算机网络·电脑