思路:
第一:生成红包队列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
//多线程处理,每个线程都需要等待上一个线程结束再执行下一个
//模拟发红包
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);
}
}