最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Redis結(jié)合SpringBoot的秒殺案例詳解

 更新時間:2021年09月29日 10:07:57   作者:別團等shy哥發(fā)育  
這篇文章主要介紹了Redis結(jié)合SpringBoot的秒殺案例,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1、構(gòu)建SpringBoot項目

搭建名為quickbuy的springboot項目,相關(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等依賴包。
項目結(jié)構(gòu)

在這里插入圖片描述

2、啟動類

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是秒殺接口,該接口包含的兩個參數(shù)是item和owner,分別表示待秒殺的商品名和發(fā)起秒殺請求的用戶。這兩個參數(shù)均被@PathVariable注解修飾,說明來自于url里的{item}和{owner}部分。
  在這個quickBuy秒殺接口中調(diào)用了SellService類里的quickBuy方法實現(xiàn)了秒殺功能,并根據(jù)SellService類quickBuy方法返回的結(jié)果,向外部返回“秒殺成功”或“秒殺失敗”的字符串語句。

4、在Service層里通過lua腳本實現(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腳本實現(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腳本,請注意傳入的參數(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();
    }
}

對lua腳本的解釋如下:

   通過ARGV[1]參數(shù)傳入發(fā)起秒殺請求的用戶,用KEYS[1]參數(shù)傳入待秒殺的商品。通過get item命令判斷item商品在Redis里還有多少庫存。
  if語句中判定剩余庫存大于等于1,就會先執(zhí)行decrby命令把庫存數(shù)減1,隨后調(diào)用第6行的rpush命令,在ownerList里記錄當(dāng)前秒殺成功的用戶,并通過return 1表示秒殺成功。如果判斷庫存數(shù)已經(jīng)小于1,那么return 0表示秒殺失敗。
  其中將lua腳本賦予redisScript對象,并通過redisTemplate.execute方法執(zhí)行l(wèi)ua腳本。

在調(diào)用redisTemplate.execute方法執(zhí)行l(wèi)ua腳本時請注意以下三點:

  • 需要以butes方式傳入腳本
  • 需要指定返回類型
  • 傳入該lua腳本所包含的KEYS類型參數(shù)的個數(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個商品

在這里插入圖片描述

6.2 啟動項目

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

在這里插入圖片描述

進(jìn)入redis查看

在這里插入圖片描述

發(fā)現(xiàn)商品數(shù)量變成了9,且能看到秒殺成功的用戶列表。

6.3 多線程形式發(fā)起秒殺請求

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個線程,線程數(shù)多余秒殺商品數(shù)
        for(int cnt=0;cnt<15;cnt++){
            new QuickBuyClients().start();
        }
    }
}
//封裝秒殺方法的工具類
class QuickBuyUtil{
    //在這個方法里,用HttpGet對象發(fā)起秒殺請求
    public static void quickBuy(){
        String user=Thread.currentThread().getName();
        CloseableHttpClient httpClient= HttpClientBuilder.create().build();
        //創(chuàng)建秒殺Get類型的url請求
        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

在這里插入圖片描述

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

在這里插入圖片描述

可以看到,15個線程秒殺商品,最終成功的只有10個。

到此這篇關(guān)于Redis結(jié)合SpringBoot的秒殺案例的文章就介紹到這了,更多相關(guān)Redis結(jié)合SpringBoot秒殺內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Redis集群增加節(jié)點與刪除節(jié)點的方法詳解

    Redis集群增加節(jié)點與刪除節(jié)點的方法詳解

    這篇文章主要給大家介紹了關(guān)于Redis集群增加節(jié)點與刪除節(jié)點的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Redis具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Redis RDB快照持久化及寫操作禁止問題排查與解決

    Redis RDB快照持久化及寫操作禁止問題排查與解決

    本文主要介紹了Redis RDB快照持久化及寫操作禁止問題排查與解決,由于?stop-writes-on-bgsave-error?選項處于啟用狀態(tài),所以寫操作被禁止,下面就來介紹一下,感興趣的可以了解一下
    2025-04-04
  • 一文了解發(fā)現(xiàn)并解決Redis熱key與大key問題

    一文了解發(fā)現(xiàn)并解決Redis熱key與大key問題

    熱key是服務(wù)端的常見問題,本文主要介紹Redis熱key與大key問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • Redis過期Key刪除策略和內(nèi)存淘汰策略的實現(xiàn)

    Redis過期Key刪除策略和內(nèi)存淘汰策略的實現(xiàn)

    當(dāng)內(nèi)存使用達(dá)到上限,就無法存儲更多數(shù)據(jù)了,為了解決這個問題,Redis內(nèi)部會有兩套內(nèi)存回收的策略,過期Key刪除策略和內(nèi)存淘汰策略,本文就來詳細(xì)的介紹一下這兩種方法,感興趣的可以了解一下
    2024-02-02
  • Redis實現(xiàn)高效內(nèi)存管理的示例代碼

    Redis實現(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
  • Redis?基本數(shù)據(jù)類型和使用詳解

    Redis?基本數(shù)據(jù)類型和使用詳解

    String是Redis?最基本的數(shù)據(jù)類型,一個鍵對應(yīng)一個值,它的功能十分強大,可以存儲字符串、整數(shù)、浮點數(shù)等多種數(shù)據(jù)格式,本文給大家介紹Redis基本數(shù)據(jù)類型和使用,感興趣的朋友一起看看吧
    2025-09-09
  • Redis三種特殊數(shù)據(jù)類型的具體使用

    Redis三種特殊數(shù)據(jù)類型的具體使用

    本文主要介紹了Redis三種特殊數(shù)據(jù)類型的具體使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • 使用Redis有序集合實現(xiàn)IP歸屬地查詢詳解

    使用Redis有序集合實現(xiàn)IP歸屬地查詢詳解

    這篇文章主要介紹了使用Redis有序集合實現(xiàn)IP歸屬地查詢,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Redis出現(xiàn)中文亂碼的問題及解決

    Redis出現(xiàn)中文亂碼的問題及解決

    這篇文章主要介紹了Redis出現(xiàn)中文亂碼的問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-06-06
  • Redis緩存鍵清理問題解決

    Redis緩存鍵清理問題解決

    對于使用redis作為緩存服務(wù)器的開發(fā)者而言,定期清除redis中的緩存數(shù)據(jù)是非常必要的,本文主要介紹了Redis緩存鍵清理問題解決,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06

最新評論

贵阳市| 揭阳市| 垦利县| 新兴县| 西和县| 佳木斯市| 阿克苏市| 鄂温| 林甸县| 宁国市| 齐齐哈尔市| 错那县| 河北省| 漾濞| 宜兰市| 玛多县| 阜平县| 吉木萨尔县| 错那县| 汝南县| 阳信县| 灵丘县| 塔城市| 长沙县| 西丰县| 麦盖提县| 惠来县| 东乌珠穆沁旗| 万荣县| 麻江县| 淳安县| 昌吉市| 贵溪市| 岫岩| 柘城县| 陵水| 上饶市| 江孜县| 白城市| 凤山县| 藁城市|