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序列号的更多相关文章

  1. SQL获取刚插入的记录的自动增长列ID的值

    假设表结构如下: CREATE TABLE TestTable ( id int identity, CreatedDate datetime ) SQL2005获得新增行的自动增长列的语句如下: i ...

  2. 使用强类型DataSet增加数据并获取自动增长的ID

    使用强类型的DataSet可以方便的操作数据库:有时候我们会对表的ID设置为自动增长,并且需要在插入数据后获取新插入数据的ID,按以下方法即可达到目的: 一.     首先建立一个表,id为自动增加, ...

  3. 使用JDBC获取SQL自动增长的ID

    在项目开发中,遇到一个问题,先添加一条记录然后想立刻获取这条记录的ID值,ID由SQLServer自动增长的,如果先插入再查询的话,需要另外执行一条查询ID的SQL语句,因此有了下面的方法: 1.使用 ...

  4. sql server生成自动增长的字母数字字符串

    在开发的过程中,我们经常会遇到要生成一些固定格式字符串,例如“BX201903150001”,结构为:BX+日期+N位序号,类似这种的字符串我们很难生成,在这里我们借助一个存储过程来实现这个功能. 1 ...

  5. 写出一条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 ...

  6. 写出一条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 ...

  7. oracle 12c之前用sequence 和 trigger来生成自动增长的列

    SQL> create table scott.t1 (id number, val varchar2(8)); Table created. SQL> CREATE SEQUENCE s ...

  8. java项目实现流水号自动增长

    项目中有一个规则编号字段,从1开始,编号长度为5位,那么第一条数据编号就是00001. 实现的基本思路就是项目启动时,从数据库获取当前最大值,作为静态变量存储: 业务获取新的编码,考虑并发问题,获取编 ...

  9. spring boot:redis+lua实现顺序自增的唯一id发号器(spring boot 2.3.1)

    一,为什么需要生成唯一id(发号器)? 1,在分布式和微服务系统中, 生成唯一id相对困难, 常用的方式: uuid不具备可读性,作为主键存储时性能也不够好, mysql的主键,在分库时使用不够方便, ...

随机推荐

  1. java开发编译器:中间语言格式

    阅读博客的朋友可以到我的网易云课堂中,通过视频的方式查看代码的调试和执行过程: http://study.163.com/course/courseMain.htm?courseId=10028300 ...

  2. nginx 学习笔记(3) nginx管理

    nginx可以通过向其发送信号来进行管理.默认情况下主进程的进程ID写到文件/usr/local/nginx/logs/nginx.pid中.当然也可以在配置文件中自定义该pid文件,自定义使用pid ...

  3. rails 过滤掉所有的html标签 strip_tags

      strip_tags(html) Strips all HTML tags from the html, including comments. This usesthe html-scanner ...

  4. SpringMVC源码阅读:Controller中参数解析

    1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...

  5. SQL中的go、begin、end的用法

    go 向 SQL Server 实用工具发出一批 Transact-SQL 语句结束的信号.go是把t-sql语句分批次执行.(一步成功了才会执行下一步,即一步一个go) BEGIN 和 END 语句 ...

  6. WCF DEMO1 创建自托管宿主

    using System; using System.ServiceModel; using System.ServiceModel.Channels; //注意:需要引用程序集 System.Ser ...

  7. 利用SignalR来同步更新Winfrom小试

    之前写了个用Socket来更新多个Winfrom的试例,这两天看了下SignalR,也用这个来试一下 SignalR 地址:https://www.asp.net/signalr 我这个也是基于 ht ...

  8. jstack,jmap,jstat分别的意义

    1.Jstack 1.1   jstack能得到运行java程序的java stack和native stack的信息.可以轻松得知当前线程的运行情况.如下图所示 注:这个和thread dump是同 ...

  9. PHPCMS V9标签循环嵌套调用数据的方法

    PHPCMS V9的标签制作以灵活见长,可以自由DIY出个性的数据调用,对于制作有风格有创意的网站模板很好用,今天就介绍一个标签循环嵌套方法,可以实现对PC标签循环调用,代码如下: 在此文件里/php ...

  10. ArcGIS Server集群布署

    ArcGIS Server集群布署 准备如下的4台机器: 计算机名 IP 布署软件 说明 VMWIN2008ENSS1 192.168.1.111 ArcGIS for Server   VMWIN2 ...