Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of grabbing red packet function through redis script lua

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the method of grabbing the red packet function through the redis script lua, the content is clear, interested friends can learn, I believe it will be helpful after reading.

Introduction to redis script

Starting with version 2.6, Redis supports the Lua environment through embedded support.

Benefits

Reduce network overhead. Multiple requests can be sent at once in the form of a script, reducing network delay to atomic operations. Redis executes the whole script as a whole without being inserted by other commands, so there is no need to worry about the reuse of race conditions during script execution. The script sent by the client is permanently saved in redis and can be reused.

Database table design

Two simple tables, a red packet form and a red packet receipt record form

CREATE TABLE `ttimered` (`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT 'ID', `quantit` decimal (10volume 2) DEFAULT NULL COMMENT' amount', `num` int (11) DEFAULT NULL COMMENT 'quantity (divided into several parts)', `update_ time`datetime DEFAULT NULL COMMENT 'creation time', `update_ time`datetime DEFAULT NULL COMMENT 'update time, PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COMMENT=' red packet' CREATE TABLE `ttimeredaccountaccoune` (`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT 'id'' `datetime DEFAULT NULL COMMENT id`bigint (20) DEFAULT NULL COMMENT 'user id', `reward` decimal (10datetime DEFAULT NULL COMMENT 2) DEFAULT NULL COMMENT' get reward', `update_ id`bigint (20) DEFAULT NULL COMMENT 'red packet id', `create_ time`time`creation time', `update_ time`time`update time', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COMMENT=' red packet collection record'

Code writing

First of all, generate a red packet, divide it into a specified number of random small red packets, and store it in reids with list structure (envelope:redEnvelopeId: red packet id as key) (in order to grab the red packet pop-up data)

Public Long divideRedEnvelope (int amount, int num) {/ * each person gets at least one penny. If there are 2000 points and 6 people, randomly get five numbers less than 1994 (2000-6) * for example, a1century, 4Magi, a2century, 120pm, a3cm, 324th, 500th, 5th, 700th (sorted by five randomly obtained numbers) So the money for red packets is: a1mema2mura1memea3mera2fu1rea4lica3light1jina5mera4q1jing1994 RedEnvelope redEnvelope a5151( the sum is exactly 2000) * / color = new RedEnvelope () RedEnvelope.setAmount (new BigDecimal (amount)); redEnvelope.setNum (num); redEnvelope.setCreateTime (new Date ()); redEnvelope.setUpdateTime (new Date ()); redEnvelopeDao.insert (redEnvelope); / * int totalAmount = amount * 100-num; / * * Random number * / int [] randomNum = new int [num-1] / * Red packet amount * / int [] redEnvelopeAmount = new int [num]; for (int I = 0; I < num-1; iTunes +) {int rand = new Random (). NextInt (totalAmount); randomNum [I] = rand;} Arrays.sort (randomNum); / * * the first, last, middle red packet assigned by the conditional statement * / for (int I = 0; I < num) If +) {redEnvelopeAmount [I] = randomNum [I] + 1;} else if (I = = num-1) {redEnvelopeAmount [I] = totalAmount-randomNum [I-1] + 1;} else {redEnvelopeAmount [I] = randomNum [I]-randomNum [I-1] + 1 Key generated by}} / * is stored in reids in list * / String key = "envelope:redEnvelopeId:" + redEnvelope.getId (); Boolean flag = stringRedisTemplate.hasKey (key); if (! flag) {for (Integer I: redEnvelopeAmount) {stringRedisTemplate.opsForList (). LeftPush (key, I + ");}} return redEnvelope.getId ();}

When grabbing red packets, generate KEYS [1], KEYS [2], KEYS [3] (key for storing small red packets, key for receiving red packet records, key for user userId) according to user userId and red packet id, and pass them into the script.

​ 1. First determine whether the user has snatched a red packet. If so, return-1. If not, take out a small red packet from the list of red packets.

If the small red packet of ​ 2 and step 1 is empty, it means that the red packet has not been snatched up. Return-2

​ 3. Otherwise, return the amount of small red packets taken out.

Public String grabRedEnvelope (Long userId, Long redEnvelopeId) {DefaultRedisScript redisScript = new DefaultRedisScript (); redisScript.setResultType (String.class); redisScript.setScriptText (LuaScript.redLua); List keyList = new ArrayList (); / * * small red packet key * / keyList.add ("envelope:redEnvelopeId:" + redEnvelopeId); / * * red packet collection record key * / keyList.add ("envelope:record:" + redEnvelopeId); keyList.add ("" + userId) KeyList.add (String.valueOf (userId)); / *-1 has grabbed the red packet-2 the red packet is over, the rest is to grab the red packet and return the balance of the red packet * / String result = stringRedisTemplate.execute (redisScript, keyList); return result;}

Realize the Lua script for grabbing red packets

Public class LuaScript {/ *-1 has grabbed red packets-2 red packets have been robbed of re red packet amount. Keys [1], keys [2] and keys [3] are key for storing small red packets, red packet receiving record key, user id * / public static String redLua = "if redis.call ('hexists',KEYS [2], KEYS [3]) ~ = 0 then\ n" + "return'-1', respectively. \ n "+" else\ n "+ local re=redis.call ('rpop',KEYS [1]);\ n" + "if re then\ n" + "redis.call (' hset',KEYS [2], KEYS [3], 1);\ n" + "return re;\ n" + "else\ n" + "return'- 2";\ n "+" end\ n "+" end ";}

test

First of all, the red packet is allocated through the interface to generate a red packet with a share of 10 pieces, and its mysql database and redis

Carry out pressure test and grab red packets through jmeter

Result

After reading the above content, do you have a better understanding of the method of grabbing red packets through redis's script lua? if you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report