基于Redis結(jié)合SpringBoot的秒殺案例詳解
1、構(gòu)建SpringBoot項(xiàng)目
搭建名為quickbuy的springboot項(xiàng)目,相關(guān)的依賴包如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.13.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baizhi</groupId>
<artifactId>quickbuy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>quickbuy</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
引入了Redis、HttpClient等依賴包。
項(xiàng)目結(jié)構(gòu)

2、啟動(dòng)類
package com.baizhi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuickbuyApplication {
public static void main(String[] args) {
SpringApplication.run(QuickbuyApplication.class, args);
}
}
3、在Controller層里定義秒殺接口
@RestController
public class QuickBuyController {
@Autowired
private SellService sellService;
@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";
}
}
}
通過@RequestMapping注解們可以把"/quickBuy/{item}/{owner}"格式的url映射到quickBuy方法上。
quickBuy是秒殺接口,該接口包含的兩個(gè)參數(shù)是item和owner,分別表示待秒殺的商品名和發(fā)起秒殺請(qǐng)求的用戶。這兩個(gè)參數(shù)均被@PathVariable注解修飾,說明來自于url里的{item}和{owner}部分。
在這個(gè)quickBuy秒殺接口中調(diào)用了SellService類里的quickBuy方法實(shí)現(xiàn)了秒殺功能,并根據(jù)SellService類quickBuy方法返回的結(jié)果,向外部返回“秒殺成功”或“秒殺失敗”的字符串語句。
4、在Service層里通過lua腳本實(shí)現(xiàn)秒殺效果
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;
@Service
public class SellService {
@Resource
private RedisTemplate redisTemplate;
public String quickBuy(String item, String owner) {
//用lua腳本實(shí)現(xiàn)秒殺
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<String> redisScript=new DefaultRedisScript<String>();
redisScript.setScriptText(luaScript);
//調(diào)用lua腳本,請(qǐng)注意傳入的參數(shù)
Object luaResult=redisTemplate.execute((RedisConnection connection)->connection.eval(
redisScript.getScriptAsString().getBytes(),
ReturnType.INTEGER,
1,
key.getBytes(),
args.getBytes()
));
//根據(jù)lua腳本的執(zhí)行情況返回結(jié)果
return luaResult.toString();
}
}
對(duì)lua腳本的解釋如下:
通過ARGV[1]參數(shù)傳入發(fā)起秒殺請(qǐng)求的用戶,用KEYS[1]參數(shù)傳入待秒殺的商品。通過get item命令判斷item商品在Redis里還有多少庫(kù)存。
if語句中判定剩余庫(kù)存大于等于1,就會(huì)先執(zhí)行decrby命令把庫(kù)存數(shù)減1,隨后調(diào)用第6行的rpush命令,在ownerList里記錄當(dāng)前秒殺成功的用戶,并通過return 1表示秒殺成功。如果判斷庫(kù)存數(shù)已經(jīng)小于1,那么return 0表示秒殺失敗。
其中將lua腳本賦予redisScript對(duì)象,并通過redisTemplate.execute方法執(zhí)行l(wèi)ua腳本。
在調(diào)用redisTemplate.execute方法執(zhí)行l(wèi)ua腳本時(shí)請(qǐng)注意以下三點(diǎn):
- 需要以butes方式傳入腳本
- 需要指定返回類型
- 傳入該lua腳本所包含的KEYS類型參數(shù)的個(gè)數(shù)是1.
- 傳入的KEYS和ARGV類型的參數(shù)需要轉(zhuǎn)換成bytes類型
5、配置redis連接參數(shù)
application.properties
server.port=8081 spring.redis.host=192.168.159.22 spring.redis.port=6379
6、演示秒殺效果
6.1 準(zhǔn)備redis環(huán)境
我用的剛搭建的redis主從復(fù)制集群,一主二從

設(shè)置10個(gè)商品

6.2 啟動(dòng)項(xiàng)目
在瀏覽器訪問http://localhost:8081/quickBuy/Computer/abc,測(cè)試秒殺接口,該url傳入的商品名是“Computer”,需要和上面設(shè)置的商品名稱一致,傳入的發(fā)起秒殺請(qǐng)求的客戶端名字為abc。輸入該url后,能看到表示秒殺成功的如下輸出。

進(jìn)入redis查看

發(fā)現(xiàn)商品數(shù)量變成了9,且能看到秒殺成功的用戶列表。
6.3 多線程形式發(fā)起秒殺請(qǐng)求
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) {
//開啟15個(gè)線程,線程數(shù)多余秒殺商品數(shù)
for(int cnt=0;cnt<15;cnt++){
new QuickBuyClients().start();
}
}
}
//封裝秒殺方法的工具類
class QuickBuyUtil{
//在這個(gè)方法里,用HttpGet對(duì)象發(fā)起秒殺請(qǐng)求
public static void quickBuy(){
String user=Thread.currentThread().getName();
CloseableHttpClient httpClient= HttpClientBuilder.create().build();
//創(chuàng)建秒殺Get類型的url請(qǐng)求
HttpGet httpGet=new HttpGet("http://localhost:8081/quickBuy/Computer/"+user);
//得到響應(yīng)結(jié)果
CloseableHttpResponse res=null;
try{
res=httpClient.execute(httpGet);
HttpEntity responseEntity=res.getEntity();
if(res.getStatusLine().equals("200")&&responseEntity!=null){
System.out.println("秒殺結(jié)果:"+ EntityUtils.toString(responseEntity));
}
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
//回收http連接資源
if(httpClient!=null){
httpClient.close();
}
if(res!=null){
res.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
先重新設(shè)置商品數(shù)量為10

啟動(dòng)上面的程序
再次進(jìn)入Redis查看商品數(shù)量和秒殺成功的用戶

可以看到,15個(gè)線程秒殺商品,最終成功的只有10個(gè)。
到此這篇關(guān)于Redis結(jié)合SpringBoot的秒殺案例的文章就介紹到這了,更多相關(guān)Redis結(jié)合SpringBoot秒殺內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot+Redis隊(duì)列實(shí)現(xiàn)Java版秒殺的示例代碼
- Springboot+redis+Vue實(shí)現(xiàn)秒殺的項(xiàng)目實(shí)踐
- springboot?+rabbitmq+redis實(shí)現(xiàn)秒殺示例
- SpringBoot+RabbitMQ+Redis實(shí)現(xiàn)商品秒殺的示例代碼
- SpringBoot之使用Redis實(shí)現(xiàn)分布式鎖(秒殺系統(tǒng))
- SpringBoot使用Redisson實(shí)現(xiàn)分布式鎖(秒殺系統(tǒng))
- springboot集成redis實(shí)現(xiàn)簡(jiǎn)單秒殺系統(tǒng)
- 基于SpringBoot+Redis+Lua 實(shí)現(xiàn)高并發(fā)秒殺系統(tǒng)
相關(guān)文章
Redis集群增加節(jié)點(diǎn)與刪除節(jié)點(diǎn)的方法詳解
這篇文章主要給大家介紹了關(guān)于Redis集群增加節(jié)點(diǎn)與刪除節(jié)點(diǎn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Redis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
一文了解發(fā)現(xiàn)并解決Redis熱key與大key問題
熱key是服務(wù)端的常見問題,本文主要介紹Redis熱key與大key問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
Redis過期Key刪除策略和內(nèi)存淘汰策略的實(shí)現(xiàn)
當(dāng)內(nèi)存使用達(dá)到上限,就無法存儲(chǔ)更多數(shù)據(jù)了,為了解決這個(gè)問題,Redis內(nèi)部會(huì)有兩套內(nèi)存回收的策略,過期Key刪除策略和內(nèi)存淘汰策略,本文就來詳細(xì)的介紹一下這兩種方法,感興趣的可以了解一下2024-02-02
Redis實(shí)現(xiàn)高效內(nèi)存管理的示例代碼
Redis內(nèi)存管理是其核心功能之一,為了高效地利用內(nèi)存,Redis采用了多種技術(shù)和策略,如優(yōu)化的數(shù)據(jù)結(jié)構(gòu)、內(nèi)存分配策略、內(nèi)存回收、數(shù)據(jù)壓縮等,下面就來詳細(xì)的介紹一下2025-08-08

