搶紅包的需求分析
搶紅包的場(chǎng)景有點(diǎn)像秒殺,但是要比秒殺簡(jiǎn)單點(diǎn)。
因?yàn)槊霘⑼ǔR蛶?kù)存相關(guān)。而搶紅包則可以允許有些紅包沒有被搶到,因?yàn)榘l(fā)紅包的人不會(huì)有損失,沒搶完的錢再退回給發(fā)紅包的人即可。
另外像小米這樣的搶購(gòu)也要比淘寶的要簡(jiǎn)單,也是因?yàn)橄裥∶走@樣是一個(gè)公司的,如果有少量沒有搶到,則下次再搶,人工修復(fù)下數(shù)據(jù)是很簡(jiǎn)單的事。而像淘寶這么多商品,要是每一個(gè)都存在著修復(fù)數(shù)據(jù)的風(fēng)險(xiǎn),那如果出故障了則很麻煩。
基于redis的搶紅包方案
下面介紹一種基于Redis的搶紅包方案。
把原始的紅包稱為大紅包,拆分后的紅包稱為小紅包。
1.小紅包預(yù)先生成,插到數(shù)據(jù)庫(kù)里,紅包對(duì)應(yīng)的用戶ID是null。生成算法見另一篇文章:https://www.jb51.net/article/98620.htm
2.每個(gè)大紅包對(duì)應(yīng)兩個(gè)redis隊(duì)列,一個(gè)是未消費(fèi)紅包隊(duì)列,另一個(gè)是已消費(fèi)紅包隊(duì)列。開始時(shí),把未搶的小紅包全放到未消費(fèi)紅包隊(duì)列里。
未消費(fèi)紅包隊(duì)列里是json字符串,如{userId:'789', money:'300'}。
3.在redis中用一個(gè)map來過濾已搶到紅包的用戶。
4.搶紅包時(shí),先判斷用戶是否搶過紅包,如果沒有,則從未消費(fèi)紅包隊(duì)列中取出一個(gè)小紅包,再push到另一個(gè)已消費(fèi)隊(duì)列中,最后把用戶ID放入去重的map中。
5.用一個(gè)單線程批量把已消費(fèi)隊(duì)列里的紅包取出來,再批量update紅包的用戶ID到數(shù)據(jù)庫(kù)里。
上面的流程是很清楚的,但是在第4步時(shí),如果是用戶快速點(diǎn)了兩次,或者開了兩個(gè)瀏覽器來?yè)尲t包,會(huì)不會(huì)有可能用戶搶到了兩個(gè)紅包?
為了解決這個(gè)問題,采用了lua腳本方式,讓第4步整個(gè)過程是原子性地執(zhí)行。
下面是在redis上執(zhí)行的Lua腳本:
-- 函數(shù):嘗試獲得紅包,如果成功,則返回json字符串,如果不成功,則返回空
-- 參數(shù):紅包隊(duì)列名, 已消費(fèi)的隊(duì)列名,去重的Map名,用戶ID
-- 返回值:nil 或者 json字符串,包含用戶ID:userId,紅包ID:id,紅包金額:money
-- 如果用戶已搶過紅包,則返回nil
if rediscall('hexists', KEYS[3], KEYS[4]) ~= 0 then
return nil
else
-- 先取出一個(gè)小紅包
local hongBao = rediscall('rpop', KEYS[1]);
if hongBao then
local x = cjsondecode(hongBao);
-- 加入用戶ID信息
x['userId'] = KEYS[4];
local re = cjsonencode(x);
-- 把用戶ID放到去重的set里
rediscall('hset', KEYS[3], KEYS[4], KEYS[4]);
-- 把紅包放到已消費(fèi)隊(duì)列里
rediscall('lpush', KEYS[2], re);
return re;
end
end
return nil
下面是測(cè)試代碼:
public class TestEval {
static String host = "localhost";
static int honBaoCount = 1_0_0000;
static int threadCount = 20;
static String hongBaoList = "hongBaoList";
static String hongBaoConsumedList = "hongBaoConsumedList";
static String hongBaoConsumedMap = "hongBaoConsumedMap";
static Random random = new Random();
// -- 函數(shù):嘗試獲得紅包,如果成功,則返回json字符串,如果不成功,則返回空
// -- 參數(shù):紅包隊(duì)列名, 已消費(fèi)的隊(duì)列名,去重的Map名,用戶ID
// -- 返回值:nil 或者 json字符串,包含用戶ID:userId,紅包ID:id,紅包金額:money
static String tryGetHongBaoScript =
// "local bConsumed = rediscall('hexists', KEYS[3], KEYS[4]);\n"
// + "print('bConsumed:' ,bConsumed);\n"
"if rediscall('hexists', KEYS[3], KEYS[4]) ~= 0 then\n"
+ "return nil\n"
+ "else\n"
+ "local hongBao = rediscall('rpop', KEYS[1]);\n"
// + "print('hongBao:', hongBao);\n"
+ "if hongBao then\n"
+ "local x = cjsondecode(hongBao);\n"
+ "x['userId'] = KEYS[4];\n"
+ "local re = cjsonencode(x);\n"
+ "rediscall('hset', KEYS[3], KEYS[4], KEYS[4]);\n"
+ "rediscall('lpush', KEYS[2], re);\n"
+ "return re;\n"
+ "end\n"
+ "end\n"
+ "return nil";
static StopWatch watch = new StopWatch();
public static void main(String[] args) throws InterruptedException {
// testEval();
generateTestData();
testTryGetHongBao();
}
static public void generateTestData() throws InterruptedException {
Jedis jedis = new Jedis(host);
jedisflushAll();
final CountDownLatch latch = new CountDownLatch(threadCount);
for(int i = 0; i threadCount; ++i) {
final int temp = i;
Thread thread = new Thread() {
public void run() {
Jedis jedis = new Jedis(host);
int per = honBaoCount/threadCount;
JSONObject object = new JSONObject();
for(int j = temp * per; j (temp+1) * per; j++) {
objectput("id", j);
objectput("money", j);
jedislpush(hongBaoList, objecttoJSONString());
}
latchcountDown();
}
};
threadstart();
}
latchawait();
}
static public void testTryGetHongBao() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(threadCount);
Systemerrprintln("start:" + SystemcurrentTimeMillis()/1000);
watchstart();
for(int i = 0; i threadCount; ++i) {
final int temp = i;
Thread thread = new Thread() {
public void run() {
Jedis jedis = new Jedis(host);
String sha = jedisscriptLoad(tryGetHongBaoScript);
int j = honBaoCount/threadCount * temp;
while(true) {
Object object = jediseval(tryGetHongBaoScript, 4, hongBaoList, hongBaoConsumedList, hongBaoConsumedMap, "" + j);
j++;
if (object != null) {
// Systemoutprintln("get hongBao:" + object);
}else {
//已經(jīng)取完了
if(jedisllen(hongBaoList) == 0)
break;
}
}
latchcountDown();
}
};
threadstart();
}
latchawait();
watchstop();
Systemerrprintln("time:" + watchgetTotalTimeSeconds());
Systemerrprintln("speed:" + honBaoCount/watchgetTotalTimeSeconds());
Systemerrprintln("end:" + SystemcurrentTimeMillis()/1000);
}
}
測(cè)試結(jié)果20個(gè)線程,每秒可以搶2.5萬個(gè),足以應(yīng)付絕大部分的搶紅包場(chǎng)景。
如果是真的應(yīng)付不了,拆分到幾個(gè)redis集群里,或者改為批量搶紅包,也足夠應(yīng)付。
總結(jié):
redis的搶紅包方案,雖然在極端情況下(即redis掛掉)會(huì)丟失一秒的數(shù)據(jù),但是卻是一個(gè)擴(kuò)展性很強(qiáng),足以應(yīng)付高并發(fā)的搶紅包方案。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Nginx+Lua+Redis構(gòu)建高并發(fā)Web應(yīng)用
- Redis實(shí)現(xiàn)高并發(fā)計(jì)數(shù)器
- 如何利用Redis鎖解決高并發(fā)問題詳解
- Redis瞬時(shí)高并發(fā)秒殺方案總結(jié)
- PHP實(shí)現(xiàn)Redis單據(jù)鎖以及防止并發(fā)重復(fù)寫入
- jedispool連redis高并發(fā)卡死的問題
- 使用lua+redis解決發(fā)多張券的并發(fā)問題