zoukankan      html  css  js  c++  java
  • SpringBoot前后端分离Instant时间戳自定义解析

    在SpringBoot项目中,前后端规定传递时间使用时间戳(精度ms).

    @Data
    public class Incident {
        @ApiModelProperty(value = "故障ID", example = "1")
        private Integer id;
        @ApiModelProperty(value = "故障产生时间", allowEmptyValue = true)
        private Instant createdTime;
        @ApiModelProperty(value = "故障恢复时间", allowEmptyValue = true)
        private Instant recoveryTime;
    }
    

    以上为简略实体类定义.

        @Transactional(rollbackFor = Exception.class)
        @PostMapping(path = "/incident")
        public void AddIncident(@Valid @RequestBody Incident incident) {
    
            incident.setBusinessId(0);
            if (1 != incidentService.addIncident(incident)) {
                throw new Exception("...");
            }
        }
    

    在实际使用过程中,发现Incident中的createdTime以及recoveryTime数值不对.
    排查故障,前端去除时间戳后三位(即ms数),则时间基本吻合.
    因此,可以确定是SpringBoot在转换Instant时使用Second进行转换.

    因此对于Instant类型的转换添加自定义解析(SpringBoot使用com.fasterxml.jackson解析数据).
    注意,.此处需要分别实现序列化(后端返回前端数据)以及反序列化(前端上传数据).

    public class InstantJacksonDeserialize extends JsonDeserializer<Instant> {
        @Override
        public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            String text = jsonParser.getText();
            Long aLong = Long.valueOf(text);
            Instant res = Instant.ofEpochMilli(aLong);
            return res;
        }
    }
    
    public class InstantJacksonSerializer extends JsonSerializer<Instant> {
        @Override
        public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeNumber(instant.toEpochMilli());
        }
    }
    

    在涉及到Instant的属性上加上相应注解,代码具体如下:

    @Data
    public class Incident {
        @ApiModelProperty(value = "故障ID", example = "1")
        private Integer id;
        @JsonSerialize(using = InstantJacksonSerializer.class)
        @JsonDeserialize(using = InstantJacksonDeserialize.class)
        @ApiModelProperty(value = "故障产生时间", allowEmptyValue = true)
        private Instant createdTime;
        @JsonSerialize(using = InstantJacksonSerializer.class)
        @JsonDeserialize(using = InstantJacksonDeserialize.class)
        @ApiModelProperty(value = "故障恢复时间", allowEmptyValue = true)
        private Instant recoveryTime;
    }
    

    添加注解后,Instant对象能够按照ms精度进行解析.

    PS:
    如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!

  • 相关阅读:
    HTTP POST GET 本质区别详解
    追求代码质量: 监视圈复杂度
    【置顶】用Eclipse开发Android应用程序索引贴
    Android访问WCF服务(上篇)服务端开发
    做一个T型技术人才
    创新创业大讲堂第一讲
    河海嵌芯FTP服务器开通运行
    嵌芯队团队邮箱以及邮件订阅功能使用说明
    基于视频的公共事件检测分析系统
    感知交通基于视频的交通流特征参数监测及交通综合信息服务系统
  • 原文地址:https://www.cnblogs.com/jason1990/p/10028262.html
Copyright © 2011-2022 走看看