search
HomeDatabaseRedisHow to use Redis+Lua script to implement the anti-swipe function of the counter interface

    [Implementation process]

    1. Problem analysis

    If the set command is set, but when setting the expiration time, the network jitters If the setting is not successful due to other reasons, a dead counter (similar to a deadlock) will occur;

    2. Solution

    Redis Lua is a good solution. Use a script to make set The command and expire command are executed together with Redis without being interfered with, which guarantees atomic operations to a large extent;

    Why is it said that atomic operations are guaranteed to a large extent but not completely? Because problems may occur when Redis is executed internally, but the probability is very small; even for small-probability events, there are corresponding solutions, such as solving deadlocks. An idea worth referring to: Preventing deadlocks will store the lock value as a time Stamp, even if the expiration time is not set, when judging whether to lock, you can add it to see if the value exceeds a set time from now. If it exceeds, delete it and reset the lock.

    3. Code transformation

    1. Implementation of Redis Lua lock

    package han.zhang.utils;
     
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.script.DigestUtils;
    import org.springframework.data.redis.core.script.RedisScript;
    import java.util.Collections;
    import java.util.UUID;
    public class RedisLock {
        private static final LogUtils logger = LogUtils.getLogger(RedisLock.class);
        private final StringRedisTemplate stringRedisTemplate;
        private final String lockKey;
        private final String lockValue;
        private boolean locked = false;
        /**
         * 使用脚本在redis服务器执行这个逻辑可以在一定程度上保证此操作的原子性
         * (即不会发生客户端在执行setNX和expire命令之间,发生崩溃或失去与服务器的连接导致expire没有得到执行,发生永久死锁)
         * <p>
         * 除非脚本在redis服务器执行时redis服务器发生崩溃,不过此种情况锁也会失效
         */
        private static final RedisScript<Boolean> SETNX_AND_EXPIRE_SCRIPT;
        static {
            StringBuilder sb = new StringBuilder();
            sb.append("if (redis.call(&#39;setnx&#39;, KEYS[1], ARGV[1]) == 1) then\n");
            sb.append("\tredis.call(&#39;expire&#39;, KEYS[1], tonumber(ARGV[2]))\n");
            sb.append("\treturn true\n");
            sb.append("else\n");
            sb.append("\treturn false\n");
            sb.append("end");
            SETNX_AND_EXPIRE_SCRIPT = new RedisScriptImpl<>(sb.toString(), Boolean.class);
        }
        private static final RedisScript<Boolean> DEL_IF_GET_EQUALS;
            sb.append("if (redis.call(&#39;get&#39;, KEYS[1]) == ARGV[1]) then\n");
            sb.append("\tredis.call(&#39;del&#39;, KEYS[1])\n");
            DEL_IF_GET_EQUALS = new RedisScriptImpl<>(sb.toString(), Boolean.class);
        public RedisLock(StringRedisTemplate stringRedisTemplate, String lockKey) {
            this.stringRedisTemplate = stringRedisTemplate;
            this.lockKey = lockKey;
            this.lockValue = UUID.randomUUID().toString() + "." + System.currentTimeMillis();
        private boolean doTryLock(int lockSeconds) {
            if (locked) {
                throw new IllegalStateException("already locked!");
            }
            locked = stringRedisTemplate.execute(SETNX_AND_EXPIRE_SCRIPT, Collections.singletonList(lockKey), lockValue,
                    String.valueOf(lockSeconds));
            return locked;
         * 尝试获得锁,成功返回true,如果失败立即返回false
         *
         * @param lockSeconds 加锁的时间(秒),超过这个时间后锁会自动释放
        public boolean tryLock(int lockSeconds) {
            try {
                return doTryLock(lockSeconds);
            } catch (Exception e) {
                logger.error("tryLock Error", e);
                return false;
         * 轮询的方式去获得锁,成功返回true,超过轮询次数或异常返回false
         * @param lockSeconds       加锁的时间(秒),超过这个时间后锁会自动释放
         * @param tryIntervalMillis 轮询的时间间隔(毫秒)
         * @param maxTryCount       最大的轮询次数
        public boolean tryLock(final int lockSeconds, final long tryIntervalMillis, final int maxTryCount) {
            int tryCount = 0;
            while (true) {
                if (++tryCount >= maxTryCount) {
                    // 获取锁超时
                    return false;
                }
                try {
                    if (doTryLock(lockSeconds)) {
                        return true;
                    }
                } catch (Exception e) {
                    logger.error("tryLock Error", e);
                    Thread.sleep(tryIntervalMillis);
                } catch (InterruptedException e) {
                    logger.error("tryLock interrupted", e);
         * 解锁操作
        public void unlock() {
            if (!locked) {
                throw new IllegalStateException("not locked yet!");
            locked = false;
            // 忽略结果
            stringRedisTemplate.execute(DEL_IF_GET_EQUALS, Collections.singletonList(lockKey), lockValue);
        private static class RedisScriptImpl<T> implements RedisScript<T> {
            private final String script;
            private final String sha1;
            private final Class<T> resultType;
            public RedisScriptImpl(String script, Class<T> resultType) {
                this.script = script;
                this.sha1 = DigestUtils.sha1DigestAsHex(script);
                this.resultType = resultType;
            @Override
            public String getSha1() {
                return sha1;
            public Class<T> getResultType() {
                return resultType;
            public String getScriptAsString() {
                return script;
    }

    2. Implementation of Redis Lua counter by using lock for reference

    (1) Tool class​​​

    package han.zhang.utils;
     
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.script.DigestUtils;
    import org.springframework.data.redis.core.script.RedisScript;
    import java.util.Collections;
    public class CountUtil {
        private static final LogUtils logger = LogUtils.getLogger(CountUtil.class);
        private final StringRedisTemplate stringRedisTemplate;
        /**
         * 使用脚本在redis服务器执行这个逻辑可以在一定程度上保证此操作的原子性
         * (即不会发生客户端在执行setNX和expire命令之间,发生崩溃或失去与服务器的连接导致expire没有得到执行,发生永久死计数器)
         * <p>
         * 除非脚本在redis服务器执行时redis服务器发生崩溃,不过此种情况计数器也会失效
         */
        private static final RedisScript<Boolean> SET_AND_EXPIRE_SCRIPT;
        static {
            StringBuilder sb = new StringBuilder();
            sb.append("local visitTimes = redis.call(&#39;incr&#39;, KEYS[1])\n");
            sb.append("if (visitTimes == 1) then\n");
            sb.append("\tredis.call(&#39;expire&#39;, KEYS[1], tonumber(ARGV[1]))\n");
            sb.append("\treturn false\n");
            sb.append("elseif(visitTimes > tonumber(ARGV[2])) then\n");
            sb.append("\treturn true\n");
            sb.append("else\n");
            sb.append("end");
            SET_AND_EXPIRE_SCRIPT = new RedisScriptImpl<>(sb.toString(), Boolean.class);
        }
        public CountUtil(StringRedisTemplate stringRedisTemplate) {
            this.stringRedisTemplate = stringRedisTemplate;
        public boolean isOverMaxVisitTimes(String key, int seconds, int maxTimes) throws Exception {
            try {
                return stringRedisTemplate.execute(SET_AND_EXPIRE_SCRIPT, Collections.singletonList(key), String.valueOf(seconds), String.valueOf(maxTimes));
            } catch (Exception e) {
                logger.error("RedisBusiness>>>isOverMaxVisitTimes; get visit times Exception; key:" + key + "result:" + e.getMessage());
                throw new Exception("already Over MaxVisitTimes");
            }
        private static class RedisScriptImpl<T> implements RedisScript<T> {
            private final String script;
            private final String sha1;
            private final Class<T> resultType;
            public RedisScriptImpl(String script, Class<T> resultType) {
                this.script = script;
                this.sha1 = DigestUtils.sha1DigestAsHex(script);
                this.resultType = resultType;
            @Override
            public String getSha1() {
                return sha1;
            public Class<T> getResultType() {
                return resultType;
            public String getScriptAsString() {
                return script;
    }

    (2) Call test code

     public void run(String... strings) {
            CountUtil countUtil = new CountUtil(SpringUtils.getStringRedisTemplate());
            try {
                for (int i = 0; i < 10; i++) {
                    boolean overMax = countUtil.isOverMaxVisitTimes("zhanghantest", 600, 2);
                    if (overMax) {
                        System.out.println("超过i:" + i + ":" + overMax);
                    } else {
                        System.out.println("没超过i:" + i + ":" + overMax);
                    }
                }
            } catch (Exception e) {
                logger.error("Exception {}", e.getMessage());
            }
        }

    (3) Test result

    How to use Redis+Lua script to implement the anti-swipe function of the counter interface

    The above is the detailed content of How to use Redis+Lua script to implement the anti-swipe function of the counter interface. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

    Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

    一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

    实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

    Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

    详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

    实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

    一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

    本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

    redis error什么意思redis error什么意思Jun 17, 2019 am 11:07 AM

    redis error就是redis数据库和其组合使用的部件出现错误,这个出现的错误有很多种,例如Redis被配置为保存数据库快照,但它不能持久化到硬盘,用来修改集合数据的命令不能用。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version