生成的雪花算法ID前端接收到的不一致问题处理
问题描述
在sharding jdbc 分表操作使用雪花算法来生成ID. 在接口返回结果前打印雪花id为823816043670536192
在前端接口收到的返回值为823816043670536100
初步判断为long类型精度丢失
问题原因
Long类型继承的是number类, 而number类的精度为16位, 生成的雪花ID长度为18位, 所以最后2位精度丢失, 统一用00替补最后2位
最终返回给前端的就是823816043670536100
解决方案
统一将返回的long类型id改为字符串类型, 这样就不会丢失精度
- 通过全局配置调整
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
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;
}
}
- 通过配置文件配置
在application.yml中加上以下配置,这个办法会将所有数字都变成字符串,包括long和int类型
spring:
jackson:
generator:
writeNumbersAsStrings: true
- 对应的返回字段上加注解
@JsonSerialize(using = ToStringSerializer.class)
@ApiModelProperty(value = "主键", example = "")
private Long id;