redis的常见操作 您所在的位置:网站首页 ioc和dl redis的常见操作

redis的常见操作

#redis的常见操作| 来源: 网络整理| 查看: 265

方案1 :使用redis的incr自增实现唯一序号,

实现1

private static String QUOTATION_PREFIX = "BJD"; private static String QUOTATION_INIT = "0000";public String generateQuotationNumber() { //格式:T+yyyyMMdd+4位流水 StringBuffer sbuffer = new StringBuffer(); sbuffer.append(QUOTATION_PREFIX); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sbuffer.append(sdf.format(new Date())); // 拼接好流水号的前缀 String incKey = sbuffer.toString(); String no = incr(incKey, 1); sbuffer.append(no); return sbuffer.toString(); } public String incr(String key, long liveTime) { // 基于这个key创建一个redis的值,默认的value为0 RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, stringRedisTemplate.getConnectionFactory()); // 对于这个key进行自增1的操作 然后返回自增1 之前的数据 Long increment = entityIdCounter.getAndIncrement(); // 如果为0 则是第一次创建这个可以,则设置这个key的过期时间为1天 if ((null == increment || increment.longValue() == 0) & liveTime > 0) {//初始设置过期时间 entityIdCounter.expire(liveTime, TimeUnit.DAYS); //设置自增值过期时间,liveTime 过期时间;TimeUnit.DAYS 过期时间单位,我这边设置为天 } // 拿到这个key进行操作,组合出满足要求的数据 if (increment == 0) { increment = increment + 1; } else if (increment > 9999) { increment = 1L; } //位数不够,前面补0 DecimalFormat df = new DecimalFormat(QUOTATION_INIT); return df.format(increment); }

代码详解

stringRedisTemplate.getConnectionFactory() 返回redis的生成工厂

RedisAtomicLong在创建的时候,会基于这个key在redis创建一个键值对,初始value为0,

getAndIncrement 最终调用的是increment方法,对这个键进行+1操作,返回返回值进行-1,这样就对redis的值进行了自增,返回自增之前的值



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有