一、现象与分析
1.1. 现象
雪花算法得到的ID较长,传到前端后,精度丢失。id后面的值debug后发现后面几位都是0
1.2. 分析
库中存的值:73235752873468712
后端取的值:73235752873468712
前端得到值:73235752873468712,数据被四舍五入了==>结果会变成73235752873468700
前端再传到后端时:73235752873468700
看到后面几位莫名其妙变成000的时候,那就要思考精度丢失的原因了
Number精度是16位(雪花ID是19位的),So:JS的Number数据类型导致的精度丢失。
二、解决方案
将Long类型转成String,再传给前端
建议使用统一的配置类
/**
* 解决前后端交互Long类型精度丢失的问题
*
* @author xusj
* <br>CreateDate 2022/8/22 10:40
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//全局配置序列化返回json处理
SimpleModule simpleModule = new SimpleModule();
//json Long ==>String
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
=================》2022.08.28 甲乙Rocket 8月第四周