搶紅包的需求分析
搶紅包的場(chǎng)景有點(diǎn)像秒殺,但是要比秒殺簡(jiǎn)單點(diǎn)。
因?yàn)槊霘⑼ǔR蛶?kù)存相關(guān)。而搶紅包則可以允許有些紅包沒(méi)有被搶到,因?yàn)榘l(fā)紅包的人不會(huì)有損失,沒(méi)搶完的錢(qián)再退回給發(fā)紅包的人即可。
另外像小米這樣的搶購(gòu)也要比淘寶的要簡(jiǎn)單,也是因?yàn)橄裥∶走@樣是一個(gè)公司的,如果有少量沒(méi)有搶到,則下次再搶?zhuān)斯ば迯?fù)下數(shù)據(jù)是很簡(jiǎn)單的事。而像淘寶這么多商品,要是每一個(gè)都存在著修復(fù)數(shù)據(jù)的風(fēng)險(xiǎn),那如果出故障了則很麻煩。
基于redis的搶紅包方案
下面介紹一種基于Redis的搶紅包方案。
把原始的紅包稱(chēng)為大紅包,拆分后的紅包稱(chēng)為小紅包。
1.小紅包預(yù)先生成,插到數(shù)據(jù)庫(kù)里,紅包對(duì)應(yīng)的用戶(hù)ID是null。生成算法見(jiàn)另一篇文章:https://www.jb51.net/article/98620.htm
2.每個(gè)大紅包對(duì)應(yīng)兩個(gè)redis隊(duì)列,一個(gè)是未消費(fèi)紅包隊(duì)列,另一個(gè)是已消費(fèi)紅包隊(duì)列。開(kāi)始時(shí),把未搶的小紅包全放到未消費(fèi)紅包隊(duì)列里。
未消費(fèi)紅包隊(duì)列里是json字符串,如{userId:'789', money:'300'}。
3.在redis中用一個(gè)map來(lái)過(guò)濾已搶到紅包的用戶(hù)。
4.搶紅包時(shí),先判斷用戶(hù)是否搶過(guò)紅包,如果沒(méi)有,則從未消費(fèi)紅包隊(duì)列中取出一個(gè)小紅包,再push到另一個(gè)已消費(fèi)隊(duì)列中,最后把用戶(hù)ID放入去重的map中。
5.用一個(gè)單線(xiàn)程批量把已消費(fèi)隊(duì)列里的紅包取出來(lái),再批量update紅包的用戶(hù)ID到數(shù)據(jù)庫(kù)里。
上面的流程是很清楚的,但是在第4步時(shí),如果是用戶(hù)快速點(diǎn)了兩次,或者開(kāi)了兩個(gè)瀏覽器來(lái)?yè)尲t包,會(huì)不會(huì)有可能用戶(hù)搶到了兩個(gè)紅包?
為了解決這個(gè)問(wèn)題,采用了lua腳本方式,讓第4步整個(gè)過(guò)程是原子性地執(zhí)行。
下面是在redis上執(zhí)行的Lua腳本:
-- 函數(shù):嘗試獲得紅包,如果成功,則返回json字符串,如果不成功,則返回空 -- 參數(shù):紅包隊(duì)列名, 已消費(fèi)的隊(duì)列名,去重的Map名,用戶(hù)ID -- 返回值:nil 或者 json字符串,包含用戶(hù)ID:userId,紅包ID:id,紅包金額:money -- 如果用戶(hù)已搶過(guò)紅包,則返回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); -- 加入用戶(hù)ID信息 x['userId'] = KEYS[4]; local re = cjsonencode(x); -- 把用戶(hù)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名,用戶(hù)ID // -- 返回值:nil 或者 json字符串,包含用戶(hù)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è)線(xiàn)程,每秒可以搶2.5萬(wàn)個(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í)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:澳門(mén) 唐山 林芝 揚(yáng)州 香港 景德鎮(zhèn) 廣東 贛州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《詳解利用redis + lua解決搶紅包高并發(fā)的問(wèn)題》,本文關(guān)鍵詞 詳解,利用,redis,lua,解決,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。