java+redis+lua生成自动增长的ID序列号
1.编写lua脚本用于生成主键ID序列号,内容如下
local key = tostring(KEYS[1]);
local count = tonumber(KEYS[2]);
local dateStr = tostring(KEYS[3]);
local newKey = key .. "_" .. dateStr;
local numRedis = redis.call("incr", newKey);
print(numRedis);
if (numRedis == 1) then
redis.call("expire",newKey,60);
end
-- 计算数字的位数
local function DightNum(num)
if math.floor(num) ~= num or num < 0 then
return -1;
elseif 0 == num then
return 1;
else
local tmp_dight = 0;
while num > 0 do
num = math.floor(num/10);
tmp_dight = tmp_dight + 1;
end
return tmp_dight;
end
end
-- 在整数数字前面加0
-- dest_dight 标识最终生成位数,例如 AddZeroFrontNum(5, 1) 计算后是00001
local function AddZeroFrontNum(dest_dight, num)
local num_dight = DightNum(num);
if -1 == num_dight then
return -1;
elseif dest_dight <= num_dight then
return tostring(num);
else
local str_e = ""
for var =1, dest_dight - num_dight do
str_e = str_e .. "0";
end
return str_e .. tostring(num);
end
end
local idStr = AddZeroFrontNum(count, numRedis);
return dateStr .. idStr;
2.redis加载lua脚本文件
redis-cli -a redis script load "$(cat getGenerateId.lua)"
"b3d58fe8b47b1ca1e1fb074db5c3506a09ffdae8"
-a: redis密码,如果没有密码,该项不需要输入
下面的字符串即为加载后redis保存的sha值,通过该sha值可以访问lua脚本
3.java代码执行缓存的lua脚本文件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
@Service
public class RedisService {
private static final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
@Autowired
private RedisTemplate<String, String> redisTemplate;
public Object executeScript(final String sha, final List<String> keys, final ArrayList<String> vals) {
return redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
Jedis jedis = (Jedis) connection.getNativeConnection();
return jedis.evalsha(sha, keys, vals);
}
}, true);
}
/**
* 每秒从 1 开始生成唯一标识,包括时间戳:yyyyMMddHHmmss
* 最终格式为:yyyyMMddHHmmss + 四位有序数字
* @param sha redis中生成lua脚本的序列号
* @param key redis中存放id的key前缀
* @param length 后面生成有序数字的位数
* @return
*/
public Long fetchUUID(String sha, String key, String length){
List<String> keys = new ArrayList<>();
keys.add(key);
keys.add(length);
Calendar now = new GregorianCalendar();
String datetime = df.format(now.getTime());
keys.add(datetime);
Object obj = executeScript(sha, keys, new ArrayList<String>());
return Long.parseLong(String.valueOf(obj));
}
}
然后调用fetchUUID该方法就可以了,key和length自定义,sha为第二步生成值
java+redis+lua生成自动增长的ID序列号的更多相关文章
- SQL获取刚插入的记录的自动增长列ID的值
假设表结构如下: CREATE TABLE TestTable ( id int identity, CreatedDate datetime ) SQL2005获得新增行的自动增长列的语句如下: i ...
- 使用强类型DataSet增加数据并获取自动增长的ID
使用强类型的DataSet可以方便的操作数据库:有时候我们会对表的ID设置为自动增长,并且需要在插入数据后获取新插入数据的ID,按以下方法即可达到目的: 一. 首先建立一个表,id为自动增加, ...
- 使用JDBC获取SQL自动增长的ID
在项目开发中,遇到一个问题,先添加一条记录然后想立刻获取这条记录的ID值,ID由SQLServer自动增长的,如果先插入再查询的话,需要另外执行一条查询ID的SQL语句,因此有了下面的方法: 1.使用 ...
- sql server生成自动增长的字母数字字符串
在开发的过程中,我们经常会遇到要生成一些固定格式字符串,例如“BX201903150001”,结构为:BX+日期+N位序号,类似这种的字符串我们很难生成,在这里我们借助一个存储过程来实现这个功能. 1 ...
- 写出一条Sql语句:取出表A中第31到第40记录(SQLServer,以自动增长的ID作为主键,注意:ID可能不是连续的。
答:解1: select top 10 * from A where id not in (select top 30 id from A) 解2: select top 10 * from A ...
- 写出一条Sql语句:取出表Customer中第31到第40记录(SQLServer,以自动增长的Id作为主键,注意:Id可能不是连续的。
select top 10 * from (select ROW_NUMBER() over(order by Id) as rows,* from Customer) as C where C.ro ...
- oracle 12c之前用sequence 和 trigger来生成自动增长的列
SQL> create table scott.t1 (id number, val varchar2(8)); Table created. SQL> CREATE SEQUENCE s ...
- java项目实现流水号自动增长
项目中有一个规则编号字段,从1开始,编号长度为5位,那么第一条数据编号就是00001. 实现的基本思路就是项目启动时,从数据库获取当前最大值,作为静态变量存储: 业务获取新的编码,考虑并发问题,获取编 ...
- spring boot:redis+lua实现顺序自增的唯一id发号器(spring boot 2.3.1)
一,为什么需要生成唯一id(发号器)? 1,在分布式和微服务系统中, 生成唯一id相对困难, 常用的方式: uuid不具备可读性,作为主键存储时性能也不够好, mysql的主键,在分库时使用不够方便, ...
随机推荐
- 尝试用selenium+appium运行一个简单的demo报错:could not get xcode version. /Library/Developer/Info.plist doest not exist on disk
业余时间抽空搭了个appium+selenium的环境(mac), 在执行第一个脚本的时候遇到个问题纪录下: could not get xcode version. /Library/Develop ...
- 微信小程序之特殊效果及功能
一.下拉刷新效果 假设页面为index文件,那么代码如下: index.json: { "enablePullDownRefresh": true } index.js: //下拉 ...
- 深入了解Java虚拟机(3-1)虚拟机类加载机制
虚拟机类加载机制 一.类加载的阶段和时机 1.阶段 整个生命周期包括:加载(Loading).验证(Verification).准备(Preparation).解析(Resolution).初始化(I ...
- Django控制器
配置路由 通过对urls.py的配置将用户请求映射到处理函数. Django的URL字符串匹配实际上基于正则表达式,这允许单条URL可以匹配一类请求.参见Django Book中的示例: from d ...
- C#.NET下转换泛型列表为JSON格式
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Te ...
- C# list的合并
转自:https://www.cnblogs.com/liguanghui/archive/2011/11/09/2242309.html List<int> listA = new Li ...
- 《码出高效 Java开发手册》第五章 异常与日志
码云: https://gitee.com/forxiaoming/JavaBaseCode/blob/master/EasyCoding/src/exception/index.md 5.2 try ...
- VS2013平台安装Qt插件过程
1.下载所需安装包: Qt5.3.Qt插件下载地址:http://qt-project.org/downloads. qt-vs-addin-1.1.11-opensource.exe 下载地址:ht ...
- PHP CURL库学习
基本请求步骤 : // . 初始化 $ch = curl_init(); // . 设置选项,包括URL curl_setopt($ch, CURLOPT_URL, "http://www. ...
- JS数组与对象的遍历方法大全
本文简单解析各种数组和对象属性的遍历方法: 原生for循环.for-in及forEach ES6 for-of方法遍历类数组集合 Object.key()返回键名的集合 jQuery的$.each() ...