栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

利用Redis和Lua的原子性实现抢红包功能

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用Redis和Lua的原子性实现抢红包功能

其实8月的时候就准备搞这个抢红包业务,代替消费后每天固定红包的业务。但后来公司发展需要,希望固定返利维持现状,红包功能戛然而止。写到简书做个记录。

设计思路:

准备3个队列

第一:生成红包队列hongBaoList,比如100元,分成10个,每个红包在10元上下波动,波动范围在[min, max],并呈现一个正态分布。这个point不是我在这里分享的关键,大家可以click进这条link:http://www.jb51.net/article/98620.htm,看下生成算法见的一篇文章。

第二:已消费的红包队列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来解决抢红包高并发的问题。

实现步骤:

1:按照http://www.jb51.net/article/98620.htm ,写一个生成红包的类HongBaoCreateUtil,:

import java.util.Random;public class HongBaoCreateUtil {  
static Random random = new Random();  
static {  
    random.setSeed(System.currentTimeMillis());  
}  
  
public static void main(String[] args) {  
    long max = 3;  
    long min = 1;  

    long[] result = HongBaoCreateUtil.generate(10, 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]);  
    }  
}  
  
  static long xRandom(long min, long max) {  
    return sqrt(nextLong(sqr(max - min)));  
}  

  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;  
}  
}

2.将生成的红包放进redis的hongBaoList

static public void generateTestData() throws InterruptedException {  
    Jedis jedis = new Jedis(host, port); 
    jedis.flushAll();  
    
    int total = 10;//10块红包
    int count  = 5;//分成5份
    long max = 3;  //最大值3块
    long min = 1;  //最小值1块

    long[] result = HongBaoCreateUtil.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());  
    }
    jedis.close();
}

main函数run一下,在RedisDesktopManager下观察:

hongBaoList.png

成功将五个红包塞进redis

3.写线程模拟抢红包:

    static String tryGetHongBaoscript =   
        "if redis.call('hexists', KEYS[3], KEYS[4]) ~= 0 thenn"  
        + "return niln"  
        + "elsen"  
        + "local hongBao = redis.call('rpop', KEYS[1]);n"  
        + "if hongBao thenn"  
        + "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"  
        + "endn"  
        + "endn"  
        + "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, 
                            "" + j  
                            );  
                    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);  
}

其中tryGetHongBaoscript 是lua脚本:

打个断点,main函数debug一下:

程序运行到一半时:

多了已消费了的红包:hongBaoConsumedList;去重表:hongBaoConsumedMap


3list

之前红包列表少了两个包:


l1.png

已消费的红包列表hongBaoConsumedList多了两条数据:


l3.png

去重表hongBaoConsumedMap多了两条用户的id:


l2.png

程序运行完成后时,只剩下hongBaoConsumedList和hongBaoConsumedMap,hongBaoConsumedList如图:


接下来的工作就是宣布谁是手气最佳,和把hongBaoConsumedList的数据塞到Database里面。

参考:
红包生成算法:http://www.jb51.net/article/98620.htm
白贺翔老师之前的Redis+Lua视频

             

作者:Michael孟良

链接:https://www.jianshu.com/p/b58ed2fe6976

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245591.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号