0051利用Redis实现业务主键的自增

需求描述:自增主键的格式为 业务序列+当前日期+从00001开始自增

//redis实现按业务+日期+自增

//输出结果为:biz2020021800001biz2020021800002biz2020021800003的形式
@Test
public void testJedis(){
    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
    Date date=new Date();
    String formatDate=sdf.format(date);
    //业务编码+日期做为rediskey
   
String key = "biz" + formatDate;

 //关键是使用RedisAtomicLong类来实现,能够保证原子性

    RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
    //取出redis中存放的值,从1开始自增
   
Long increment =entityIdCounter.incrementAndGet();
    //将值转换为指定位数
   
DecimalFormat df=new DecimalFormat("00000");//五位序列号
   
String value = df.format(increment);
    //键与值拼接做为自增主键
   
System.out.println(key + value);
    }

以上是单线程的情况进行测试,也可以通过下面多线程的方式进行测试

public void testMoreThread()throws Exception{    ExecutorService executorService = Executors.newFixedThreadPool(100);    for(int i=1;i<=1000;i++){        executorService.execute(new Runnable() {            @Override            public void run() {                System.out.println("当前线程为:" + Thread.currentThread().getName());                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");                Date date=new Date();                String formatDate=sdf.format(date);                //业务编码+日期做为redis的key                String key = "biz" + formatDate;                RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());                //取出redis中存放的值,从1开始自增                Long increment = entityIdCounter.incrementAndGet();                //将值转换为指定位数                DecimalFormat df=new DecimalFormat("00000");//五位序列号                String value = df.format(increment);                //键与值拼接做为自增主键                System.out.println("业务主键为:"+key + value);            }        });    }//一定要有这两行代码,否则上边的for循环中的线程还没有执行完,线程池就关闭了,然后就会报错连接不上redis    Thread.sleep(5000); //模拟等待执行结束    executorService.shutdown();}