美文网首页
客户端通过SpringCloud调用服务端,服务端返回值包含da

客户端通过SpringCloud调用服务端,服务端返回值包含da

作者: 初晨的笔记 | 来源:发表于2018-07-05 11:12 被阅读0次

1、问题排查

出现的场景:

服务端通过springmvc写了一个对外的接口,返回一个json字符串,其中该json带有日期,格式为yyyy-MM-dd HH:mm:ss

客户端通过feign调用该http接口,指定返回值为一个Dto,Dto中日期的字段为Date类型

客户端调用该接口后抛异常了。

报错异常如下:

10:38:50 [ERROR]   >> com.syt.firefly.cloud.service.cms.CmsManageController:35
feign.codec.DecodeException: JSON parse error: Can not deserialize value of type java.util.Date from String "2018-07-04 13:32:50": not a valid representation (error: Failed to parse Date value '2018-07-04 13:32:50': Can not parse date "2018-07-04 13:32:50": while it seems to fit format 'yy
yy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not
 deserialize value of type java.util.Date from String "2018-07-04 13:32:50": not a valid representation (error: Failed to parse Date value '2018-
07-04 13:32:50': Can not parse date "2018-07-04 13:32:50": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? nul
l))
 at [Source: java.io.PushbackInputStream@6fdf3c74; line: 1, column: 654] (through reference chain: java.util.ArrayList[0]->com.syt.firefly.cloud.
service.cms.bean.ClassicCaseVo["created"])
    at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:169)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:133)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    at com.sun.proxy.$Proxy146.getList(Unknown Source)
    at com.syt.firefly.cloud.service.cms.CmsManageController.getList(CmsManageController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  • 从异常信息中我们可以看出,是在AbstractJackson2HttpMessageConverter类中调用了readJavaType方法之后抛的异常

  • 一步一步往下深入,我们找到了最关键的地方,在DeserializationContext类的_parseDate方法中,执行了df.parse(dateStr)之后抛异常了

public Date parseDate(String dateStr) throws IllegalArgumentException
{
    try {
        DateFormat df = getDateFormat();
        // 这行代码报错了
        return df.parse(dateStr);
    } catch (ParseException e) {
        throw new IllegalArgumentException(String.format(
                "Failed to parse Date value '%s': %s", dateStr, e.getMessage()));
    }
}

  • DeserializationContext是jackson的一个反序列化的一个上下文,那么它的DateFormat是从哪来的呢?我们再来看下getDateFormat的源码
protected DateFormat getDateFormat()
{
    if (_dateFormat != null) {
        return _dateFormat;
    }
    DateFormat df = _config.getDateFormat();
    _dateFormat = df = (DateFormat) df.clone();
    return df;
}

  • DateFormat又是从MapperConfig而来,我们再看下config.getDateFormat()的源码
public final DateFormat getDateFormat() { return _base.getDateFormat(); }

2、问题处理

  • 异常说的值服务器返回了一个带有日期的json,日期的形式是字符串2018-03-07 16:18:35,jackson无法将该字符串转成一个Date对象,网上查资料,上面说的是jackson只支持以下几种日期格式:

  • "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

  • "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

  • "yyyy-MM-dd";

  • "EEE, dd MMM yyyy HH:mm:ss zzz";

  • long类型的时间戳

  • 去掉服务端的以下两个配置,让日期返回时间戳,结果就没报错了

#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.time-zone=Asia/Chongqing
  • 由于服务端在其他的地方有可能和这里的配置耦合了,也就是说其他地方有可能要用到的是yyyy-MM-dd HH:mm:ss这一日期格式而不是时间戳的格式,所以这个配置肯定是不能修改的。

  • jackson竟然不支持yyyy-MM-dd HH:mm:ss的这种格式,肯定很不爽啦,所以下面就要开始来研究怎么让jackson支持这种格式了。

  • 要让jackson支持这种格式,那么就必须修改ObjectMapper中的DateFormat,因为在ObjectMapper中,DateFormat的默认实现类是StdDateFormat,StdDateFormat也就只兼容了我们上述所说的几种格

  • 首先我们先使用装饰模式来创建一个支持yyyy-MM-dd HH:mm:ss格式的DateFormat如下

 
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class MyDateFormat extends DateFormat {
 
    private DateFormat dateFormat;
 
    private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
 
    public MyDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }
 
    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }
 
    @Override
    public Date parse(String source, ParsePosition pos) {
 
        Date date = null;
 
        try {
 
            date = format1.parse(source, pos);
        } catch (Exception e) {
 
            date = dateFormat.parse(source, pos);
        }
 
        return date;
    }
 
    // 主要还是装饰这个方法
    @Override
    public Date parse(String source) throws ParseException {
 
        Date date = null;
 
        try {
            
            // 先按我的规则来
            date = format1.parse(source);
        } catch (Exception e) {
 
            // 不行,那就按原先的规则吧
            date = dateFormat.parse(source);
        }
 
        return date;
    }
 
    // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new MyDateFormat((DateFormat) format);
    }
}

  • DateFormat有了,接下来的任务就是让ObjectMapper使用我的这个DateFormat了,在config类中定义如下(本案例基于springboot)
@Configuration
public class WebConfig {
 
    @Autowired
    private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
    
    @Bean
    public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() {
 
        ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
 
        // ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
        // 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
        DateFormat dateFormat = mapper.getDateFormat();
        mapper.setDateFormat(new MyDateFormat(dateFormat));
 
        MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
                mapper);
        return mappingJsonpHttpMessageConverter;
    }
}

  • 配置了上述代码之后,问题成功解决。

3、为什么往spring容器中注入MappingJackson2HttpMessageConverter,springMvc就会用这个Converter呢?

  • 查看springboot的源代码如下:
@Configuration
class JacksonHttpMessageConvertersConfiguration {
 
    @Configuration
    @ConditionalOnClass(ObjectMapper.class)
    @ConditionalOnBean(ObjectMapper.class)
    @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true)
    protected static class MappingJackson2HttpMessageConverterConfiguration {
 
        @Bean
        @ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, ignoredType = {
                "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
                "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
        public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(
                ObjectMapper objectMapper) {
            return new MappingJackson2HttpMessageConverter(objectMapper);
        }
 
}

  • 默认配置为,当spring容器中没有MappingJackson2HttpMessageConverter这个实例的时候才会被创建

  • springboot的思想是约定优于配置,也就是说,springboot默认帮我们配好了spring mvc的Converter,如果我们没有自定义Converter的话,那么框架就会帮我们创建一个,如果我们有自定义的话,那么springboot就直接使用我们所注册的bean进行绑定

本文转自黄雄杰的博文Spring Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(Can not deserialize value of type Date from String) ,刚刚在调用过程发现这个问题,遂记录一下,谢谢原作者。

相关文章

  • 客户端通过SpringCloud调用服务端,服务端返回值包含da

    1、问题排查 出现的场景: 服务端通过springmvc写了一个对外的接口,返回一个json字符串,其中该json...

  • springcloud配置中心

    springcloud配置中心 分为服务端和客户端,客户端通过服务端的接口获取自己的配置文件。客户端不能主动的知道...

  • 一个引号引发的惨案---string转byte[]

    背景 客户端通过https请求访问服务端,校验服务端body返回值必须 =="OK",满足=="OK"业务能正常运...

  • spring cloud config

    产生的背景: 定义 配置读取规则 Springcloud config 搭建分类客户端 和服务端 (1)服务端...

  • Zookeeper(四)-客户端-核心类

    概述 zk是CS架构,用户需要通过客户端API跟服务端交互。客户端主要包含以下几个模块: 通信模块:负责跟服务端进...

  • SOFABolt 源码分析15 - 双工通信机制的设计

    SOFABolt 提供了双工通信能力,使得不仅客户端可以调用服务端,服务端也可以主动调用客户端(当然,客户端也就需...

  • 6.Framework概述

    Framework概述 Framework框架 框架包含三部分: 服务端 客户端 Linux驱动 服务端 服务端只...

  • TCP

    [toc] TCP TCP总流程 客户端、服务端:调用socket函数,创建套接字描述符 服务端调用bind函数,...

  • 纯手写node静态服务器

    客户端跟服务端的通信都是通过socket进行的。客户端跟服务端各开一个socket,客户端通过三次握手协议跟服务端...

  • Android Framework

    Android Framework包含三个内容:服务端、客户端、linux驱动 服务端 Android Frame...

网友评论

      本文标题:客户端通过SpringCloud调用服务端,服务端返回值包含da

      本文链接:https://www.haomeiwen.com/subject/sfiqyftx.html