admin管理员组

文章数量:1585963

有些时候我们可能会遇见数据库生成的ID过长,超过了前端 JS Number 类型最大值,须把 Long 型转换为 String 型,如果不转换就会出现报错现象

这个时候我们就可以使用 IdGenerator 唯一Id生成器 来生成ID且不会重复

实例如下:

 public int add(Pojo pojo)
    {
        pojo.setId(IDGenerator.next());
        return pojoMapper.insert(pojo);
    }

工具类:

import org.apachemons.lang3.RandomUtils;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author
 */
public class IDGenerator {
	private final static long BASE = 531055996252L;//减除数
	private static int serverId = 2; //2字节
	
	private static AtomicLong atoLong = new AtomicLong();
	
	public static Long next(){
		long t = (System.currentTimeMillis() - BASE);
		int random = RandomUtils.nextInt(); // .nextInt(31);//随机数
		int lowValue = ((serverId << 5) |  (random  & 0x1f));
		lowValue = (lowValue & 0x7f);
		
		BigInteger ret = ((BigInteger.valueOf(t).shiftLeft(7)).or(BigInteger.valueOf(lowValue)));
		return ret.longValue();
	}
	
	/**
	 * 消息发送场景需要的消息ID
	 * @return
	 */
	public static Long nextMid(){
		Long mid = atoLong.incrementAndGet();
		if(mid >= Integer.MAX_VALUE) {
			atoLong.set(1L);
		}
		return mid;
	}
}

本文标签: 生成器IdGeneratorid