feign调用反序列化支持多种日期格式方案

使用spring cloud feign进行接口调用时,遇到服务端返回的日期格式不一致问题,比较难要求服务端去整改,只能自己扩展feign客户端反序列化支持各种日期格式了。其中两种日期格式是:2024-09-02T08:05:06.555Z、2025-02-27T15:51:34.813121+08:00

feign默认使用jackson进行序列化和反序列化,那么解决起来也很简单,直接自定义一个ObjectMapper 注入即可

代码如下:

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(LocalDateTime.class, new MultiFormatLocalDateTimeDeserializer());

        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    public static class MultiFormatLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

        // 定义支持的多种日期格式
        private static final List<DateTimeFormatter> FORMATTERS = Arrays.asList(
                new DateTimeFormatterBuilder()
                        .appendPattern("yyyy-MM-dd[ ]['T']HH:mm:ss")
                        .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 7, true)
                        .appendPattern("[XXX][X][Z]")
                        .toFormatter()
//                下面扩展各种其他日期格式
//                DateTimeFormatter.ISO_LOCAL_DATE_TIME,
//                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'+08:00'"),
//                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
//                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'")
        );

        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String dateTimeStr = p.getText().trim();

            // 尝试用多种格式解析日期时间字符串
            for (DateTimeFormatter formatter : FORMATTERS) {
                try {
                    return LocalDateTime.parse(dateTimeStr, formatter);
                } catch (Exception e) {
                    // 如果解析失败,继续尝试下一种格式
                }
            }

            // 如果所有格式都解析失败,抛出异常
            throw new IllegalArgumentException("无法解析日期时间字符串: " + dateTimeStr);
        }
    }

### 使用 Feign 实现文件上传数组接口的调用 为了实现使用 Feign 调用文件上传数组接口的功能,可以按照以下方式构建应用程序: #### 1. 配置 Spring Boot 应用程序以支持 Feign 客户端 确保在启动类上添加 `@SpringBootApplication` 和 `@EnableFeignClients` 注解来启用 Feign 功能并指定要扫描的包路径[^3]。 ```java @SpringBootApplication @EnableFeignClients("com.example.feignclients") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 2. 创建 Feign 接口定义 定义一个带有适当 HTTP 方法签名的 Feign 接口用于处理多部分表单数据提交。这里假设目标服务提供了一个接收文件列表作为输入参数的 API 端点 `/upload/files`[^1]。 ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; @FeignClient(name = "file-upload-service", url = "${service.url}") public interface FileUploadService { @PostMapping(value = "/upload/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) String uploadFiles(@RequestPart("files") List<MultipartFile> files); } ``` #### 3. 在消费者应用中注入并使用 Feign Client 通过依赖注入获取上述定义好的 Feign 客户端实例,在业务逻辑层调用其提供的方法完成实际操作[^2]。 ```java @Service public class UploadServiceImpl implements UploadService { private final FileUploadService fileUploadService; @Autowired public UploadServiceImpl(FileUploadService fileUploadService) { this.fileUploadService = fileUploadService; } @Override public ResponseEntity<String> handleFileUpload(List<MultipartFile> multipartFiles) throws IOException { try { // Call the remote service via Feign client to perform batch uploads. String result = fileUploadService.uploadFiles(multipartFiles); return new ResponseEntity<>(result, HttpStatus.OK); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } ``` 以上就是利用 Feign 来实现批量文件上传的一个简单例子。需要注意的是,具体实现细节可能会因项目环境不同而有所差异,比如使用的序列化器/反序列化器库版本、网络配置等都可能影响最终效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值