java解决雪花算法及超长id精度缺失

现象

表的主键是id bigint,用来存储雪花算法生成的ID。

create table `test` (
  `id` bigint not null comment 'id',
  `name` varchar(50) comment '名称',
  `password` varchar(50) comment '密码',
  primary key (`id`)
) engine=innodb default charset=utf8mb4 comment='测试';

使用Long 类型对应数据库ID类型。

import lombok.Data;
 
@Data
public class Test{
    /**
     * 用户id
     */
    private Long id;
    //其他成员变量省略
}

后端断点以JSON数据响应给前端正常。

    {
      "id": "107481618557435904",
       ...
    }

实际在前端展示

107481618557435904-----------------------107481618557435900

※ 服务端Long类型的id,正常。前端JSON字符串转js对象,接收Long类型的是Number,Number精度是16位(雪花ID是19位),JS的Number数据类型导致精度丢失。

解决如下

  • 将数据库表设计的id字段由 Long 类型改成 String 类型,但要考虑实际情况,String 类型做ID,查询性能会下降。
  • 前端用String类型的雪花ID保持精度,后端及数据库继续使用Long(BigINT)类型不影响数据库查询执行效率。
  • 使用Jackson进行JSON序列化的时候怎么将Long类型ID转成String响应给前端。
package com.liu.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * @ClassName : JacksonConfig
 * @Description : 雪花算法ID到前端之后精度丢失问题
 * @Author : liunian
 * @Date: 2021-06-17 14:20
 */
@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;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流年师兄要努力りゅう

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值