1. 程式人生 > >SpringBoot前後端分離Instant時間戳自定義解析

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;
    }
}

在涉及到Instant的屬性上加上相應註解,程式碼具體如下:

@Data
public class Incident {
    @ApiModelProperty(value = "故障ID", example = "1")
    private Integer id;
    @JsonDeserialize(using = InstantJacksonDeserialize.class)
    @ApiModelProperty(value = "故障產生時間", allowEmptyValue = true)
    private Instant createdTime;
    @JsonDeserialize(using = InstantJacksonDeserialize.class)
    @ApiModelProperty(value = "故障恢復時間", allowEmptyValue = true)
    private Instant recoveryTime;
}

添加註解後,Instant物件能夠按照ms精度進行解析.

PS:
如果您覺得我的文章對您有幫助,可以掃碼領取下紅包,謝謝!