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

How to realize second kill based on Redis and SpringBoot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to achieve second kill based on Redis combined with SpringBoot, the article is very detailed, has a certain reference value, interested friends must read it!

1. Build the SpringBoot project

Build a springboot project named quickbuy, and the related dependency packages are as follows:

4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.13.RELEASE com.baizhi quickbuy 0.0.1-SNAPSHOT quickbuy Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-data-redis org.springframework .boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.apache.httpcomponents httpclient 4.5.5 org.apache.httpcomponents httpcore 4.4.10 Org.springframework.boot spring-boot-maven-plugin

Dependency packages such as Redis and HttpClient are introduced.

Project structure

2. Launch class package com.baizhi;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class QuickbuyApplication {public static void main (String [] args) {SpringApplication.run (QuickbuyApplication.class, args);}} 3. Define the second kill interface @ RestControllerpublic class QuickBuyController {@ Autowired private SellService sellService in the Controller layer. @ RequestMapping ("/ quickBuy/ {item} / {owner}") public String quickbuy (@ PathVariable String item,@PathVariable String owner) {String result=sellService.quickBuy (item,owner); if (! result.equals ("0")) {return owner+ "success";} else {return owner+ "fail";}

   can map url in the format "/ quickBuy/ {item} / {owner}" to the quickBuy method through the @ RequestMapping annotation.

   quickBuy is a second kill API. The API contains two parameters, item and owner, which represent the trade name to be killed and the user who initiated the second kill request, respectively. Both parameters are modified by the @ PathVariable annotation, indicating that they come from the {item} and {owner} sections of the url.

   calls the quickBuy method in the SellService class in this quickBuy second kill API to achieve the second kill function, and returns a string statement of "second kill success" or "second kill failure" to the outside according to the result returned by the SellService class quickBuy method.

4. Achieve the second kill effect of package com.baizhi.service;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.connection.ReturnType;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.stereotype.Service;import javax.annotation.Resource;@Servicepublic class SellService {@ Resource private RedisTemplate redisTemplate through lua script in Service layer Public String quickBuy (String item, String owner) {/ / use lua script to kill String luaScript= "local owner=ARGV [1]\ n" + "local item=KEYS [1]\ n" + "local leftNum=tonumber (redis.call ('get',item))\ n" + "if (leftNum > = 1)\ n" + then redis.call (' decrby',item) 1)\ n "+" redis.call ('rpush','ownerList',owner)\ n "+" return 1\ n "+" else\ n "+" return 0\ n "+" end\ n "+"\ n " String key=item; String args=owner; DefaultRedisScript redisScript=new DefaultRedisScript (); redisScript.setScriptText (luaScript); / / call the lua script. Please note the parameter Object luaResult=redisTemplate.execute ((RedisConnection connection)-> connection.eval (redisScript.getScriptAsString (). GetBytes (), ReturnType.INTEGER, 1, key.getBytes (), args.getBytes () / / return the result return luaResult.toString ();}} according to the execution of the lua script

The lua script is explained as follows:

   passes in the user who initiated the second kill request through the ARGV [1] parameter, and uses the KEYS [1] parameter to pass in the goods to be killed. Use the get item command to determine how much item goods are in stock in Redis.

If you determine that the remaining inventory is greater than or equal to 1 in the    if statement, you will first execute the decrby command to reduce the number of inventory by 1, and then call the rpush command on line 6 to record the current second kill successful user in ownerList, and indicate the success by return 1. If it is determined that the number of inventory has been less than 1, then return 0 indicates that the second kill failed.

   where the lua script is assigned to the redisScript object and the lua script is executed through the redisTemplate.execute method.

Note the following three points when calling the redisTemplate.execute method to execute the lua script:

Script needs to be passed in butes mode

Need to specify the return type

The number of KEYS type parameters contained in the lua script passed in is 1. 0.

The parameters of the KEYS and ARGV types passed in need to be converted to bytes types

5. Configure redis connection parameters

Application.properties

Server.port=8081spring.redis.host=192.168.159.22spring.redis.port=63796, demonstrate the second kill effect 6.1 prepare the redis environment

I used the newly built redis master-slave replication cluster, one master and two slaves.

Set up 10 items

6.2 start the project

   accesses http://localhost:8081/quickBuy/Computer/abc, in the browser to test the second kill API. The trade name passed by the url is "Computer", which needs to be the same as the product name set above. The name of the client that initiates the second kill request is abc. After entering the url, you can see the following output indicating the success of the second kill.

Enter redis to view

It is found that the number of products has become 9, and you can see a list of users who have successfully killed in seconds.

6.3 initiate a second kill request in the form of multi-thread

QuickBuyClients.java

Package com.baizhi.client;import org.apache.http.HttpEntity;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;public class QuickBuyClients extends Thread {@ Override public void run () {QuickBuyUtil.quickBuy () } public static void main (String [] args) {/ / start 15 threads, the number of threads exceeds the number of seconds to kill the number of goods for (int cnt=0;cnt)

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

Development

Wechat

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

12
Report