redis+lua+紅包

思路:

第一:生成紅包隊列hongBaoList,比如100元,分成10個,每個紅包在10元上下波動,波動範圍在[min, max],並呈現一個正態分佈。

第二:已消費的紅包隊列hongBaoConsumedList,就是我每消費一個紅包,hongBaoList減少一個,hongBaoConsumedList多增加一個,知道hongBaoList消費完。

第三:去重的隊列hongBaoConsumedMap,記錄已經搶了紅包的用戶ID,就是防止用戶搶多個紅包。當然放在hongBaoConsumedList也行,但比較麻煩,索性新起一個map,記錄已經搶了紅包的用戶ID,到時用redis的hexists直接判斷用戶ID有沒有在去重的Map裏面。

爲什麼用redis+lua:

第一:redis緩存的讀寫快,lua的輕量級開發。

第二:redis具有原子性,也就是單線程,所以操作紅包是安全的,但對於一個列表是安全的,對於多個列表,像hongBaoList,hongBaoConsumedList,hongBaoConsumedMap這三個列表進行邏輯操作,就需要lua腳本,lua也有原子性,而且能保證hongBaoList,hongBaoConsumedList,hongBaoConsumedMap這三個列表在同意線程下統一操作。

所以選擇redis+lua來解決搶紅包高併發的問題。

在設計之前,先了解一下redis的list的數據結構:

在這裏插入圖片描述

1、lpush+lpop=Stack(棧)

2、lpush+rpop=Queue(隊列)

3、lpsh+ltrim=Capped Collection(有限集合)

4、lpush+brpop=Message Queue(消息隊列)

我們基於lpush+rpop進行紅包的設計。

創建紅包數量及金額

public static void main(String[] args) throws InterruptedException {

    long max = 30; //紅包最大值
    long min = 10; //紅包最小值
    int money= 100;//10塊紅包
    int count  = 5;//分成5份
	
	//調用方法
    long[] result = RedDemoUtils.generate(100, count , max, min);

    long total = 0;
    for (int i = 0; i < result.length; i++) {
        System.out.println("result[" + i + "]:" + result[i]);
        System.out.println(result[i]);
        total += result[i];
    }
    //檢查生成的紅包的總額是否正確
    System.out.println("total:" + total);

    //統計每個錢數的紅包數量,檢查是否接近正態分佈
    int count[] = new int[(int) max + 1];
    for (int i = 0; i < result.length; i++) {
        count[(int) result[i]] += 1;
    }

    for (int i = 0; i < count.length; i++) {
        System.out.println("" + i + "  " + count[i]);
    }*/
}

/**
 * 生產min和max之間的隨機數,但是概率不是平均的,從min到max方向概率逐漸加大。
 * 先平方,然後產生一個平方值範圍內的隨機數,再開方,這樣就產生了一種“膨脹”再“收縮”的效果。
 *
 * @param min
 * @param max
 * @return
 */  static long xRandom(long min, long max) {
    return sqrt(nextLong(sqr(max - min)));
}

/**
 *
 * @param total
 *            紅包總額
 * @param count
 *            紅包個數
 * @param max
 *            每個小紅包的最大額
 * @param min
 *            每個小紅包的最小額
 * @return 存放生成的每個小紅包的值的數組
 */  public static long[] generate(long total, int count, long max, long min) {
    long[] result = new long[count];

    long average = total / count;

    long a = average - min;
    long b = max - min;

    //
    //這樣的隨機數的概率實際改變了,產生大數的可能性要比產生小數的概率要小。
    //這樣就實現了大部分紅包的值在平均數附近。大紅包和小紅包比較少。
    long range1 = sqr(average - min);
    long range2 = sqr(max - average);

    for (int i = 0; i < result.length; i++) {
        //因爲小紅包的數量通常是要比大紅包的數量要多的,因爲這裏的概率要調換過來。
        //當隨機數>平均值,則產生小紅包
        //當隨機數<平均值,則產生大紅包
        if (nextLong(min, max) > average) {
            // 在平均線上減錢
            //long temp = min + sqrt(nextLong(range1));
            long temp = min + xRandom(min, average);
            result[i] = temp;
            total -= temp;
        } else {
            // 在平均線上加錢
            //long temp = max - sqrt(nextLong(range2));
            long temp = max - xRandom(average, max);
            result[i] = temp;
            total -= temp;
        }
    }
    // 如果還有餘錢,則嘗試加到小紅包裏,如果加不進去,則嘗試下一個。
    while (total > 0) {
        for (int i = 0; i < result.length; i++) {
            if (total > 0 && result[i] < max) {
                result[i]++;
                total--;
            }
        }
    }
    // 如果錢是負數了,還得從已生成的小紅包中抽取回來
    while (total < 0) {
        for (int i = 0; i < result.length; i++) {
            if (total < 0 && result[i] > min) {
                result[i]--;
                total++;
            }
        }
    }
    return result;
}

static long sqrt(long n) {
    // 改進爲查表?
    return (long) Math.sqrt(n);
}

static long sqr(long n) {
    // 查錶快,還是直接算快?
    return n * n;
}

static long nextLong(long n) {
    return random.nextInt((int) n);
}

static long nextLong(long min, long max) {
    return random.nextInt((int) (max - min + 1)) + min;
}

生成的紅包放進redis的hongBaoList

/**
*host/port/psw 需要自行配置
*將隨機生成的紅包存儲到redis裏
*/
static public void generateTestData() throws InterruptedException {
Jedis jedis = new Jedis(host, port);
jedis.auth(psw);
// jedis.flushAll();

    int total = 100;//10塊紅包
    int count  = 5;//分成5份
    long max = 30;  //最大值3塊
    long min = 10;  //最小值1塊

    long[] result = RedDemoUtils.generate(total, count, max, min);
    JSONObject object = new JSONObject();
    for (long l : result) {
        object.put("id", l);
        object.put("money", l);
        jedis.lpush(hongBaoList, object.toJSONString());
        System.out.println(object);
    }

    jedis.close();
}

獲取存到redis裏的hongBaoList

//每個線程都需要等待上一個線程結束再執行下一個
CountDownLatch 詳解 https://yq.aliyun.com/articles/592274
//模擬發紅包
static public void testTryGetHongBao() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(threadCount);
long startTime = System.currentTimeMillis();
System.err.println(“start:” + startTime);

    for(int i = 0; i < threadCount; ++i) {
        final int temp = i;
                Jedis jedis = new Jedis(host, port);
                jedis.auth(psw);
                String sha = jedis.scriptLoad(tryGetHongBaoScript);
                int j = honBaoCount/threadCount * temp;
                while(true) {
                    //搶紅包方法

                    //object從redis裏去掉下一個要領取的紅包.且把userId 放入map去重
                    Object object = jedis.eval(tryGetHongBaoScript, 4,
                            hongBaoList,
                            hongBaoConsumedList,
                            hongBaoConsumedMap,
                            "" + j
                    );
                    j++;
                    if (object != null) {

                        //拿到紅包做業務邏輯處理

                    }else {
                        //已經取完了預先生成的紅包list若爲空
                        if(jedis.llen(hongBaoList) == 0)
                            break;
                    }
                }
                latch.countDown();
    }

    latch.await();
    long costTime =  System.currentTimeMillis() - startTime;

    System.err.println("costTime:" + costTime);
}

完整代碼

import com.alibaba.fastjson.JSONObject;
import com.sunsoft.sys.utils.UUIDUtil;
import redis.clients.jedis.Jedis;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class RedDemoUtils {
static String host = xxxx;
static int port = xxxx;
static String psw = xxxx;

static String hongBaoList = "9330e0985e8c4393a28fbc7e5180791f"; 	//預先生成的紅包list的key	
static String hongBaoConsumedList = "hongBaoConsumedList"; 		//L2 已消費的紅包隊列
static String hongBaoConsumedMap = "hongBaoConsumedMap";  		//去重的map

static int honBaoCount = 10;

static int threadCount = 10; 

static Random random = new Random();
static {
    random.setSeed(System.currentTimeMillis());
}

public static void main(String[] args) throws InterruptedException {

// RedDemoUtils.generateTestData();
RedDemoUtils.testTryGetHongBao();
/*long max = 30;
long min = 10;

    long[] result = RedDemoUtils.generate(100, 5, max, min);


    long total = 0;
    for (int i = 0; i < result.length; i++) {
        System.out.println("result[" + i + "]:" + result[i]);
        System.out.println(result[i]);
        total += result[i];
    }
    //檢查生成的紅包的總額是否正確
    System.out.println("total:" + total);

    //統計每個錢數的紅包數量,檢查是否接近正態分佈
    int count[] = new int[(int) max + 1];
    for (int i = 0; i < result.length; i++) {
        count[(int) result[i]] += 1;
    }

    for (int i = 0; i < count.length; i++) {
        System.out.println("" + i + "  " + count[i]);
    }*/
}

/**
 * 生產min和max之間的隨機數,但是概率不是平均的,從min到max方向概率逐漸加大。
 * 先平方,然後產生一個平方值範圍內的隨機數,再開方,這樣就產生了一種“膨脹”再“收縮”的效果。
 *
 * @param min
 * @param max
 * @return
 */  static long xRandom(long min, long max) {
    return sqrt(nextLong(sqr(max - min)));
}

/**
 *
 * @param total
 *            紅包總額
 * @param count
 *            紅包個數
 * @param max
 *            每個小紅包的最大額
 * @param min
 *            每個小紅包的最小額
 * @return 存放生成的每個小紅包的值的數組
 */  public static long[] generate(long total, int count, long max, long min) {
    long[] result = new long[count];

    long average = total / count;

    long a = average - min;
    long b = max - min;

    //
    //這樣的隨機數的概率實際改變了,產生大數的可能性要比產生小數的概率要小。
    //這樣就實現了大部分紅包的值在平均數附近。大紅包和小紅包比較少。
    long range1 = sqr(average - min);
    long range2 = sqr(max - average);

    for (int i = 0; i < result.length; i++) {
        //因爲小紅包的數量通常是要比大紅包的數量要多的,因爲這裏的概率要調換過來。
        //當隨機數>平均值,則產生小紅包
        //當隨機數<平均值,則產生大紅包
        if (nextLong(min, max) > average) {
            // 在平均線上減錢
            //long temp = min + sqrt(nextLong(range1));
            long temp = min + xRandom(min, average);
            result[i] = temp;
            total -= temp;
        } else {
            // 在平均線上加錢
            //long temp = max - sqrt(nextLong(range2));
            long temp = max - xRandom(average, max);
            result[i] = temp;
            total -= temp;
        }
    }
    // 如果還有餘錢,則嘗試加到小紅包裏,如果加不進去,則嘗試下一個。
    while (total > 0) {
        for (int i = 0; i < result.length; i++) {
            if (total > 0 && result[i] < max) {
                result[i]++;
                total--;
            }
        }
    }
    // 如果錢是負數了,還得從已生成的小紅包中抽取回來
    while (total < 0) {
        for (int i = 0; i < result.length; i++) {
            if (total < 0 && result[i] > min) {
                result[i]--;
                total++;
            }
        }
    }
    return result;
}

static long sqrt(long n) {
    // 改進爲查表?
    return (long) Math.sqrt(n);
}

static long sqr(long n) {
    // 查錶快,還是直接算快?
    return n * n;
}

static long nextLong(long n) {
    return random.nextInt((int) n);
}

static long nextLong(long min, long max) {
    return random.nextInt((int) (max - min + 1)) + min;
}

//將生成的紅包放進redis的hongBaoList
static public void generateTestData() throws InterruptedException {
    Jedis jedis = new Jedis(host, port);
    jedis.auth(psw);

// jedis.flushAll();

    int total = 100;//10塊紅包
    int count  = 5;//分成5份
    long max = 30;  //最大值3塊
    long min = 10;  //最小值1塊

    long[] result = RedDemoUtils.generate(total, count, max, min);
    JSONObject object = new JSONObject();
    for (long l : result) {
        object.put("id", l);
        object.put("money", l);
        jedis.lpush(hongBaoList, object.toJSONString());
        System.out.println(object);
    }

    jedis.close();
}



static String tryGetHongBaoScript =
        "if redis.call('hexists', KEYS[3], KEYS[4]) ~= 0 then\n"
                + "return nil\n"
                + "else\n"
                + "local hongBao = redis.call('rpop', KEYS[1]);\n"
                + "if hongBao then\n"
                + "local x = cjson.decode(hongBao);\n"
                + "x['userId'] = KEYS[4];\n"
                + "local re = cjson.encode(x);\n"
                + "redis.call('hset', KEYS[3], KEYS[4], KEYS[4]);\n"
                + "redis.call('lpush', KEYS[2], re);\n"
                + "return re;\n"
                + "end\n"
                + "end\n"
                + "return nil";
//模擬發紅包
static public void testTryGetHongBao() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(threadCount);
    long startTime = System.currentTimeMillis();
    System.err.println("start:" + startTime);

    for(int i = 0; i < threadCount; ++i) {
        final int temp = i;
        Thread thread = new Thread() {
            public void run() {
                Jedis jedis = new Jedis(host, port);
                String sha = jedis.scriptLoad(tryGetHongBaoScript);
                int j = honBaoCount/threadCount * temp;
                while(true) {
                    //搶紅包方法
                    Object object = jedis.eval(tryGetHongBaoScript, 4,
                            hongBaoList/*預生成的紅包隊列*/,
                            hongBaoConsumedList, /*已經消費的紅包隊列*/
                            hongBaoConsumedMap, /*去重的map*/
                            "" + j  /*用戶id*/
                    );
                    j++;
                    if (object != null) {
                        //do something...
                        //                          System.out.println("get hongBao:" + object);
                    }else {
                        //已經取完了
                        if(jedis.llen(hongBaoList) == 0)
                            break;
                    }
                }
                latch.countDown();
            }
        };
        thread.start();
    }

    latch.await();
    long costTime =  System.currentTimeMillis() - startTime;

    System.err.println("costTime:" + costTime);
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章