Table of Contents
[Implementation process]
1. Problem analysis
2. Solution
3. Code transformation
Home Database Redis How to use Redis+Lua script to implement the anti-swipe function of the counter interface

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

May 28, 2023 pm 11:32 PM
redis lua

    [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;
    }
    Copy after login

    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;
    }
    Copy after login

    (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());
            }
        }
    Copy after login

    (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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

    Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

    How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

    How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

    How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

    To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

    How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

    Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

    How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

    Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

    How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

    On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

    How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

    Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

    How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

    In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

    See all articles