服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - 基于Redis结合SpringBoot的秒杀案例详解

基于Redis结合SpringBoot的秒杀案例详解

2021-11-19 17:36别团等shy哥发育 Redis

这篇文章主要介绍了Redis结合SpringBoot的秒杀案例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、构建springboot项目

搭建名为quickbuy的springboot项目,相关的依赖包如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?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等依赖包。
项目结构

基于Redis结合SpringBoot的秒杀案例详解

2、启动类

?
1
2
3
4
5
6
7
8
9
10
11
12
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层里定义秒杀接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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是秒杀接口,该接口包含的两个参数是item和owner,分别表示待秒杀的商品名和发起秒杀请求的用户。这两个参数均被@pathvariable注解修饰,说明来自于url里的{item}和{owner}部分。
  在这个quickbuy秒杀接口中调用了sellservice类里的quickbuy方法实现了秒杀功能,并根据sellservice类quickbuy方法返回的结果,向外部返回“秒杀成功”或“秒杀失败”的字符串语句。

4、在service层里通过lua脚本实现秒杀效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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脚本实现秒杀
        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);
        //调用lua脚本,请注意传入的参数
        object luaresult=redistemplate.execute((redisconnection connection)->connection.eval(
           redisscript.getscriptasstring().getbytes(),
           returntype.integer,
           1,
           key.getbytes(),
           args.getbytes()
        ));
        //根据lua脚本的执行情况返回结果
        return luaresult.tostring();
    }
}

对lua脚本的解释如下:

   通过argv[1]参数传入发起秒杀请求的用户,用keys[1]参数传入待秒杀的商品。通过get item命令判断item商品在redis里还有多少库存。
  if语句中判定剩余库存大于等于1,就会先执行decrby命令把库存数减1,随后调用第6行的rpush命令,在ownerlist里记录当前秒杀成功的用户,并通过return 1表示秒杀成功。如果判断库存数已经小于1,那么return 0表示秒杀失败。
  其中将lua脚本赋予redisscript对象,并通过redistemplate.execute方法执行lua脚本。

在调用redistemplate.execute方法执行lua脚本时请注意以下三点:

  • 需要以butes方式传入脚本
  • 需要指定返回类型
  • 传入该lua脚本所包含的keys类型参数的个数是1.
  • 传入的keys和argv类型的参数需要转换成bytes类型

5、配置redis连接参数

application.properties

?
1
2
3
4
server.port=8081
 
spring.redis.host=192.168.159.22
spring.redis.port=6379

6、演示秒杀效果

 6.1 准备redis环境

我用的刚搭建的redis主从复制集群,一主二从

基于Redis结合SpringBoot的秒杀案例详解

设置10个商品

基于Redis结合SpringBoot的秒杀案例详解

6.2 启动项目

  在浏览器访问http://localhost:8081/quickbuy/computer/abc,测试秒杀接口,该url传入的商品名是“computer”,需要和上面设置的商品名称一致,传入的发起秒杀请求的客户端名字为abc。输入该url后,能看到表示秒杀成功的如下输出。

基于Redis结合SpringBoot的秒杀案例详解

进入redis查看

基于Redis结合SpringBoot的秒杀案例详解

发现商品数量变成了9,且能看到秒杀成功的用户列表。

6.3 多线程形式发起秒杀请求

quickbuyclients.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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个线程,线程数多余秒杀商品数
        for(int cnt=0;cnt<15;cnt++){
            new quickbuyclients().start();
        }
    }
}
//封装秒杀方法的工具类
class quickbuyutil{
    //在这个方法里,用httpget对象发起秒杀请求
    public static void quickbuy(){
        string user=thread.currentthread().getname();
        closeablehttpclient httpclient= httpclientbuilder.create().build();
        //创建秒杀get类型的url请求
        httpget httpget=new httpget("http://localhost:8081/quickbuy/computer/"+user);
        //得到响应结果
        closeablehttpresponse res=null;
        try{
            res=httpclient.execute(httpget);
            httpentity responseentity=res.getentity();
            if(res.getstatusline().equals("200")&&responseentity!=null){
                system.out.println("秒杀结果:"+ 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();
            }
        }
    }
}

先重新设置商品数量为10

基于Redis结合SpringBoot的秒杀案例详解

启动上面的程序
再次进入redis查看商品数量和秒杀成功的用户

基于Redis结合SpringBoot的秒杀案例详解

可以看到,15个线程秒杀商品,最终成功的只有10个。

到此这篇关于redis结合springboot的秒杀案例的文章就介绍到这了,更多相关redis结合springboot秒杀内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_43753724/article/details/120539253

延伸 · 阅读

精彩推荐
  • RedisRedis分布式锁升级版RedLock及SpringBoot实现方法

    Redis分布式锁升级版RedLock及SpringBoot实现方法

    这篇文章主要介绍了Redis分布式锁升级版RedLock及SpringBoot实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以...

    等不到的口琴7802021-07-25
  • Redis就这?Redis持久化策略——AOF

    就这?Redis持久化策略——AOF

    今天为大家介绍Redis的另一种持久化策略——AOF。注意:AOF文件只会记录Redis的写操作命令,因为读命令对数据的恢复没有任何意义...

    头发茂密的刘叔4052021-12-14
  • RedisRedis存取序列化与反序列化性能问题详解

    Redis存取序列化与反序列化性能问题详解

    这篇文章主要给大家介绍了关于Redis存取序列化与反序列化性能问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    这名字已经存在9742021-02-24
  • Redisredis启动,停止,及端口占用处理方法

    redis启动,停止,及端口占用处理方法

    今天小编就为大家分享一篇redis启动,停止,及端口占用处理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    澄海单挑狂5152019-11-14
  • Redis在ssm项目中使用redis缓存查询数据的方法

    在ssm项目中使用redis缓存查询数据的方法

    本文主要简单的使用Java代码进行redis缓存,即在查询的时候先在service层从redis缓存中获取数据。如果大家对在ssm项目中使用redis缓存查询数据的相关知识感...

    caychen8962019-11-12
  • Redis聊一聊Redis与MySQL双写一致性如何保证

    聊一聊Redis与MySQL双写一致性如何保证

    一致性就是数据保持一致,在分布式系统中,可以理解为多个节点中数据的值是一致的。本文给大家分享Redis与MySQL双写一致性该如何保证,感兴趣的朋友一...

    mind_programmonkey6432021-08-12
  • RedisLinux Redis 的安装步骤详解

    Linux Redis 的安装步骤详解

    这篇文章主要介绍了 Linux Redis 的安装步骤详解的相关资料,希望大家通过本文能掌握如何安装Redis,需要的朋友可以参考下 ...

    carl-zhao3822019-11-08
  • RedisRedis数据结构之链表与字典的使用

    Redis数据结构之链表与字典的使用

    这篇文章主要介绍了Redis数据结构之链表与字典的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    白泽来了4052021-08-03