java-spring基於redis單機版(redisTemplate)實現的分布式鎖+redis消息隊列,可用於秒殺,定時器,高並發,搶購


此教程不涉及整合spring整合redis,可另行查閱資料教程。

代碼:

RedisLock

package com.cashloan.analytics.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class RedisLock {
    private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
    private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100;
    public static final String LOCK_PREFIX = "redis_lock_";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 鎖超時時間,防止線程在入鎖以后,無限的執行等待
     */
    private int expireMsecs = 60 * 1000;

    /**
     * 鎖等待時間,防止線程飢餓
     */
    private int timeoutMsecs = 10 * 1000;


    public String get(final String key) {
        Object obj = null;
        try {
            obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
                StringRedisSerializer serializer = new StringRedisSerializer();
                byte[] data = connection.get(serializer.serialize(key));
                connection.close();
                if (data == null) {
                    return null;
                }
                return serializer.deserialize(data);
            });
        } catch (Exception e) {
            logger.error("get redis error, key : {}", key);
        }
        return obj != null ? obj.toString() : null;
    }

    public boolean setNX(final String key, final String value) {
        Object obj = null;
        try {
            obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
                StringRedisSerializer serializer = new StringRedisSerializer();
                Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
                connection.close();
                return success;
            });
        } catch (Exception e) {
            logger.error("setNX redis error, key : {}", key);
        }
        return obj != null ? (Boolean) obj : false;
    }

    private String getSet(final String key, final String value) {
        Object obj = null;
        try {
            obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
                StringRedisSerializer serializer = new StringRedisSerializer();
                byte[] ret = connection.getSet(serializer.serialize(key), serializer.serialize(value));
                connection.close();
                return serializer.deserialize(ret);
            });
        } catch (Exception e) {
            logger.error("setNX redis error, key : {}", key);
        }
        return obj != null ? (String) obj : null;
    }

    /**
     * 獲得 lock. 實現思路: 主要是使用了redis 的setnx命令,緩存了鎖. reids緩存的key是鎖的key,所有的共享,
     * value是鎖的到期時間(注意:這里把過期時間放在value了,沒有時間上設置其超時時間) 執行過程:
     * 1.通過setnx嘗試設置某個key的值,成功(當前沒有這個鎖)則返回,成功獲得鎖
     * 2.鎖已經存在則獲取鎖的到期時間,和當前時間比較,超時的話,則設置新的值
     *
     * @return true if lock is acquired, false acquire timeouted
     * @throws InterruptedException
     *             in case of thread interruption
     */
    public boolean lock(String lockKey) throws InterruptedException {
        lockKey = LOCK_PREFIX + lockKey;
        int timeout = timeoutMsecs;
        while (timeout >= 0) {
            long expires = System.currentTimeMillis() + expireMsecs + 1;
            String expiresStr = String.valueOf(expires); // 鎖到期時間
            if (this.setNX(lockKey, expiresStr)) {
                return true;
            }

            String currentValueStr = this.get(lockKey); // redis里的時間
            if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
                // 判斷是否為空,不為空的情況下,如果被其他線程設置了值,則第二個條件判斷是過不去的
                // lock is expired

                String oldValueStr = this.getSet(lockKey, expiresStr);
                // 獲取上一個鎖到期時間,並設置現在的鎖到期時間,
                // 只有一個線程才能獲取上一個線上的設置時間,因為jedis.getSet是同步的
                if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
                    // 防止誤刪(覆蓋,因為key是相同的)了他人的鎖——這里達不到效果,這里值會被覆蓋,但是因為什么相差了很少的時間,所以可以接受

                    // [分布式的情況下]:如過這個時候,多個線程恰好都到了這里,但是只有一個線程的設置值和當前值相同,他才有權利獲取鎖
                    return true;
                }
            }
            timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;

            /*
             * 延遲100 毫秒, 這里使用隨機時間可能會好一點,可以防止飢餓進程的出現,即,當同時到達多個進程,
             * 只會有一個進程獲得鎖,其他的都用同樣的頻率進行嘗試,后面有來了一些進行,也以同樣的頻率申請鎖,這將可能導致前面來的鎖得不到滿足.
             * 使用隨機的等待時間可以一定程度上保證公平性
             */
            Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);

        }
        return false;
    }

    /**
     * Acqurired lock release.
     */
    public void unlock(String lockKey) {
        lockKey = LOCK_PREFIX + lockKey;
        redisTemplate.delete(lockKey);
    }

}

redis消息隊列:RedisQueue

package com.cashloan.analytics.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * redis消息隊列
 */
@Component
public class RedisQueue {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /** ---------------------------------- redis消息隊列 ---------------------------------- */
    /**
     * 存值
     * @param key 鍵
     * @param value 值
     * @return
     */
    public boolean lpush(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 取值 - <rpop:非阻塞式>
     * @param key 鍵
     * @return
     */
    public Object rpop(String key) {
        try {
            return redisTemplate.opsForList().rightPop(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 取值 - <brpop:阻塞式> - 推薦使用
     * @param key 鍵
     * @param timeout 超時時間
     * @param timeUnit 給定單元粒度的時間段
     *                 TimeUnit.DAYS          //天
     *                 TimeUnit.HOURS         //小時
     *                 TimeUnit.MINUTES       //分鍾
     *                 TimeUnit.SECONDS       //秒
     *                 TimeUnit.MILLISECONDS  //毫秒
     * @return
     */
    public Object brpop(String key, long timeout, TimeUnit timeUnit) {
        try {
            return redisTemplate.opsForList().rightPop(key, timeout, timeUnit);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查看值
     * @param key 鍵
     * @param start 開始
     * @param end 結束 0 到 -1代表所有值
     * @return
     */
    public List<Object> lrange(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

測試類controller:Test

package com.cashloan.analytics.controller;

import com.cashloan.analytics.utils.RedisLock;
import com.cashloan.analytics.utils.RedisQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/test")
public class Test {
    private final static String MESSAGE = "testmq";
    @Autowired
    private RedisQueue redisQueue;
    @Autowired
    private RedisLock redisLock;

    @GetMapping("/add")
    public String add() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Map map = new HashMap();
        map.put("id", uuid);
        // 加入redis消息隊列
        redisQueue.lpush(MESSAGE, map);
        addBatch();
        return "success";
    }

    public void addBatch() {
        try {
            if (redisLock.lock(MESSAGE)) {
                List<Object> lrange = redisQueue.lrange(MESSAGE, 0, -1);
                int size = lrange.size();
                if (size >= 10) {
                    List<Map> maps = new ArrayList<>();
                    for (int i = 0; i < size; i++) {
                        Object brpop = redisQueue.rpop(MESSAGE);
                        if (brpop != null) {
                            maps.add((Map) brpop);
                        }
                    }
                    // 記錄數據
                    if (!maps.isEmpty()) {
                        for (int i = 0; i < maps.size(); i++) {
                            System.out.println(maps.get(i).get("id"));
                            Thread.sleep(100);
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redisLock.unlock(MESSAGE);
        }
    }

}

 

另有一份模擬高並發多線程請求的工具(python3):

# -*- coding: utf-8 -*-
import requests
import threading

class postrequests():
    def __init__(self):
        self.url = 'http://localhost:9090/test/add'
    def post(self):
        try:
            r = requests.get(self.url)
            print(r.text)
        except Exception as e:
            print(e)

def test():
    test = postrequests()
    return test.post()
try:
    i = 0
    # 開啟線程數目
    tasks_number = 105
    print('測試啟動')
    while i < tasks_number:
        t = threading.Thread(target=test)
        t.start()
        i += 1
except Exception as e:
    print(e)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM