redis每天生成自增流水号(001、002...)
原理:
利用redis的RedisAtomicLong类实现该功能:
让其每天第一次放置一个新的自增的值(一天过期)
然后和每天的日期相加就可以了
例子: 20180901 + 001 ;当天就是 20180901 + 002
如果要多少个0,可以自己配置(工具类中)
一、pom.xml配置
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
二、redisTemplate配置
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration
public class RedisConfig {
/**
* retemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om); // 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet(); return template;
}
}
三、代码实现
import java.util.Set;
import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
@Component
public class CacheService { //这里因为有其他的template,所以名字起得不好看
@Autowired
RedisTemplate<String, Object> ObjectRedisTemplate; public Long getIncrementNum(String key) {
// 不存在准备创建 键值对
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
Long counter = entityIdCounter.incrementAndGet();
if ((null == counter || counter.longValue() == 1)) {// 初始设置过期时间
System.out.println("设置过期时间为1天!");
entityIdCounter.expire(1, TimeUnit.DAYS);// 单位天
}
return counter;
}
}
四、工具类(可以直接添加方法)
public class SequenceUtils { static final int DEFAULT_LENGTH = 3; public static String getSequence(long seq) {
String str = String.valueOf(seq);
int len = str.length();
if (len >= DEFAULT_LENGTH) {// 取决于业务规模,应该不会到达3
return str;
}
int rest = DEFAULT_LENGTH - len;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rest; i++) {
sb.append('0');
}
sb.append(str);
return sb.toString();
}
}
五、测试
String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
Long num = cacheService.getIncrementNum("demo_get_the_new_" + "test3_"+currentDate);
String flowCode = SequenceUtils.getSequence(num);
logger.info("流水号: " + flowCode);
六、控制台输出
设置过期时间为1天!
流水号0001 设置过期时间为1天!
流水号0002
redis每天生成自增流水号(001、002...)的更多相关文章
- 【原】Redis实现生成自增流水号
场景: 公司内部有个业务场景是后台审核之后需要生成一个流水号,规则是: 201807280001,201807280002,201807280003,后面四位依次递增,前面年月日取当前时间并且转换成y ...
- java+redis+lua生成自动增长的ID序列号
1.编写lua脚本用于生成主键ID序列号,内容如下 local key = tostring(KEYS[1]); local count = tonumber(KEYS[2]); local date ...
- javascript生成表格增删改查 JavaScript动态改变表格单元格内容 动态生成表格 JS获取表格任意单元格 javascript如何动态删除表格某一行
jsp页面表格布局Html代码 <body onload="show()"> <center> <input type="text" ...
- SQLServer根据不同前缀生成多套流水号
--种子表 --@prefix 前缀 --@seed 种子值 create table RefNoSeed( prefix ) unique, seed int ) go --测试表 --@inser ...
- 如何用redis来生成唯一Id
在之前的项目中需要用到一个自动增长的主键,该主键需要包含字母,所以没有办法用到数据库的自增主键.楼主要高手的指导下,发现Redis的RedisAtomicLong类可以解决这个麻烦.而且redis为单 ...
- Redis的原子自增性
INCR key 将 key 中储存的数字值增一. 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作. 如果值包含错误的类型,或字符串类型的值不能表示为数字,那 ...
- Dynamics 365中使用计算字段自动编号字段实时工作流自动生成分组编码加流水号的自动编号字段值
我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...
- SQL 生成可配置流水号
需求背景每执行一次方法,根据公式返回最新的流水号.第一次使用时需要先插入一条数据,BizSeqValue 为流水起始号:A2014030000,Formula 为公式:A[yyyy][mm][c4], ...
- Redis初始化配置及增删改查
package com.calc.tools import redis.clients.jedis.JedisPool import redis.clients.jedis.Jedis import ...
- 东方国信 - 软件开发人员面试问卷(ver1.001.002)
1. 通用编程知识问卷(所有编程人员必做)... 1 1.1 SQL问卷... 1 1.2 翻译... 2 2. Java问卷(Java程序员应答,其他跳过)... 2 ...
随机推荐
- CMake配置跨平台项目踩的坑
当要在windows平台下使用MinGW作为cmake使用的make平台时,需要确保cmake能够在系统环境变量PATH中找到MinGW的bin目录,如果PATH中没有MinGW的话可以在CMakeL ...
- 【git】7.5 git工具-搜索
资料来源: (1) https://git-scm.com/book/zh/v2/Git-%E5%B7%A5%E5%85%B7-%E6%90%9C%E7%B4%A2 1.git grep 注1:使用g ...
- Windows支持多个远程连接
1.点击 开始-->运行-->输入"gpedit.msc",进入本地组策略编辑器 2.点击 计算机配置-->管理模板-->Windows组件-->远程 ...
- prometheus Alertmanager webhook
一.自定义邮件告警 二.使用docker部署微信机器人告警 1.制作镜像 2.启动容器和指定webhook容器 一.自定义邮件告警 在alertmanager服务的配置文件中指定自定义告警文件 # ...
- 使用Swagger和OpenAPI 3规范定义API接口并集成到SpringBoot
1. OpenAPI 3 规范介绍及属性定义 参考官方定义:https://swagger.io/specification/ 2. 使用OpenAPI 3规范定义API接口 官方样例参考:https ...
- 修改文件时mmap如何处理
拷贝二进制(elf)文件 在拷贝二进制文件的时候,如果文件是一个可执行文件,并且有一个进程在运行这个可执行文件,那么拷贝的时候会出现"文本忙"(ETXTBSY)的错误提示,并且拷贝 ...
- AES可以加密成
AES可以生成HEX的字符串如{[m9LJfF4fYtt+PGoAA5WmL+6RFh5oVvrlCQpVhLyk3l28XqS3D4Qd+ehOdvqLcUrFKcyBV3hygXHU3We33bY ...
- SqlServer outer apply(cross apply)
select * from baiduacg_cookies c cross apply (select top 1 * from product where AccountId=c.AccountI ...
- C#中的ReferenceEquals、Equals以及==
https://www.cnblogs.com/ArtofDesign/p/3615212.html C#中有一共有四种相等性判断方法: //Object中定义的三个方法 public stati ...
- Qt中的串口编程
串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口.串行接口(Serial Interface) 是指数据一位一位地顺序传送,其特点是通信线路简单,只要 ...