佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 基于Redis的List實現(xiàn)特價商品列表功能

基于Redis的List實現(xiàn)特價商品列表功能

熱門標簽:Linux服務(wù)器 服務(wù)外包 鐵路電話系統(tǒng) 百度競價排名 呼叫中心市場需求 網(wǎng)站排名優(yōu)化 地方門戶網(wǎng)站 AI電銷

 1、場景分析

淘寶京東的特價商品列表,

商品特點:

  • 商品有限,并發(fā)量非常的大。
  • 考慮分頁

傳統(tǒng)解決方案:數(shù)據(jù)庫db,

但是在如此大的并發(fā)量的情況下,不可取。

一般會采用redis來處理。這些特價商品的數(shù)據(jù)不多,而且redis的list本身也支持分頁。是天然處理這種列表的最佳選擇解決方案。

2、分析

采用list數(shù)據(jù),因為list數(shù)據(jù)結(jié)構(gòu)有:lrange key 0 -1 可以進行數(shù)據(jù)的分頁。

127.0.0.1:6379> lpush products p1 p2 p3 p4 p5 p6 p7 p8 p9 p10
(integer) 10
127.0.0.1:6379> lrange products 0 1
1) "p10"
2) "p9"
127.0.0.1:6379> lrange products 2 3
1) "p8"
2) "p7"
127.0.0.1:6379> lrange products 4 5
1) "p6"
2) "p5"

3 、具體實現(xiàn)

淘寶,京東的熱門商品在雙11的時候,可能有100多w需要搞活動:程序需要5分鐘對特價商品進行刷新。

3.1 ProductListService類

  •  初始化的活動的商品信息100個(從數(shù)據(jù)庫去查詢)

@PostContrcut使用

  •  查詢產(chǎn)品列表信息

換算的分頁的起始位置和結(jié)束位置

package com.example.service;

import com.example.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Auther: 長頸鹿
 * @Date: 2021/08/29/18:00
 * @Description:
 */
@Service
@Slf4j
public class ProductListService {

    @Autowired
    private RedisTemplate redisTemplate;

    // 數(shù)據(jù)熱加載
    @PostConstruct
    public void initData(){
        log.info("啟動定時加載特價商品到redis的list中...");
        new Thread(() -> runCourse()).start();
    }

    public void runCourse() {
        while (true) {
            // 從數(shù)據(jù)庫中查詢出特價商品
            ListProduct> productList = this.findProductsDB();
            // 刪除原來的特價商品
            this.redisTemplate.delete("product:hot:list");
            // 把特價商品添加到集合中
            this.redisTemplate.opsForList().leftPushAll("product:hot:list", productList);
            try {
                // 每隔一分鐘執(zhí)行一次
                Thread.sleep(1000 * 60);
                log.info("定時刷新特價商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 數(shù)據(jù)庫中查詢特價商品
     *
     * @return
     */
    public ListProduct> findProductsDB() {
        //ListProduct> productList = productMapper.selectListHot();
        ListProduct> productList = new ArrayList>();
        for (long i = 1; i = 100; i++) {
            Product product = new Product();
            product.setId((long) new Random().nextInt(1000));
            product.setPrice((double) i);
            product.setTitle("特價商品" + (i));
            productList.add(product);
        }
        return productList;
    }

}

3.2 商品的數(shù)據(jù)接口的定義和展示及分頁

package com.example.controller;

import com.example.entity.Product;
import com.example.service.ProductListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Auther: 長頸鹿
 * @Date: 2021/08/29/18:04
 * @Description:
 */
@RestController
public class ProductListController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductListService productListService;

    @GetMapping("/findProducts")
    public ListProduct> findProducts(int pageNo, int pageSize) {

        // 從那個集合去查詢
        String key = "product:hot:list";
        // 分頁的開始結(jié)束的換算
        if (pageNo = 0) pageNo = 1;
        int start = (pageNo - 1) * pageSize;
        // 計算分頁的結(jié)束頁
        int end = start + pageSize - 1;

        // 根據(jù)redis的api去處理分頁查詢對應(yīng)的結(jié)果
        try {
            ListProduct> productList = this.redisTemplate.opsForList().range(key, start, end);
            if (CollectionUtils.isEmpty(productList)) {
                //todo: 查詢數(shù)據(jù)庫,存在緩存擊穿的情況,大量的并發(fā)請求進來,可能把數(shù)據(jù)庫沖
                productList = productListService.findProductsDB();
            }
            return productList;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

3.3 定時任務(wù)

@Configuration      // 主要用于標記配置類,兼?zhèn)銫omponent的效果。
@EnableScheduling   // 開啟定時任務(wù)
public class SaticScheduleTask {
    // 添加定時任務(wù)
    @Scheduled(cron = "* 0/5 * * * ?")
    // 或直接指定時間間隔,例如:5秒
    // @Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("執(zhí)行靜態(tài)定時任務(wù)時間: " + LocalDateTime.now());
    }
}

4、解決商品列表存在的緩存擊穿問題

 4.1 如何引起的緩存擊穿的情況

public void runCourse() {
        while (true) {
            // 從數(shù)據(jù)庫中查詢出特價商品
            ListProduct> productList = this.findProductsDB();
            // 刪除原來的特價商品
            this.redisTemplate.delete("product:hot:list");
            // 把特價商品添加到集合中 需要時間
            this.redisTemplate.opsForList().leftPushAll("product:hot:list", productList);
            try {
                // 每隔一分鐘執(zhí)行一遍
                Thread.sleep(1000 * 60);
                log.info("定時刷新特價商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

出現(xiàn)原因:

  • 特價商品的數(shù)據(jù)更換需要時間,剛好特價商品還沒有放入到redis緩存中。
  • 查詢特價商品的并發(fā)量非常大,可能程序還正在寫入特價商品到緩存中,這時查詢緩存根本沒有數(shù)據(jù),就會直接沖入數(shù)據(jù)庫中去查詢特價商品。可能造成數(shù)據(jù)庫沖垮。這個就叫做:緩存擊穿

4.2 解決方案

主從輪詢

可以開辟兩塊redis的集合空間A和B。定時器在更新緩存的時候,先更新B緩存,然后再更新A緩存

一定要按照特定順序來處理。

package com.example.service;

import com.example.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Auther: 長頸鹿
 * @Date: 2021/08/29/18:00
 * @Description:
 */
@Service
@Slf4j
public class ProductListService {

    @Autowired
    private RedisTemplate redisTemplate;

    // 數(shù)據(jù)熱加載
    @PostConstruct
    public void initData(){
        log.info("啟動定時加載特價商品到redis的list中...");
        new Thread(() -> runCourse()).start();
    }

    public void runCourse() {
        while (true) {
            // 從數(shù)據(jù)庫中查詢出特價商品
            ListProduct> productList = this.findProductsDB();

            // 刪除原來的特價商品
            this.redisTemplate.delete("product:hot:slave:list");
            // 把特價商品添加到集合中
            this.redisTemplate.opsForList().leftPushAll("product:hot:slave:list", productList);// 刪除原來的特價商品

            this.redisTemplate.delete("product:hot:master:list");
            // 把特價商品添加到集合中
            this.redisTemplate.opsForList().leftPushAll("product:hot:master:list", productList);

//            // 刪除原來的特價商品
//            this.redisTemplate.delete("product:hot:list");
//            // 把特價商品添加到集合中
//            this.redisTemplate.opsForList().leftPushAll("product:hot:list", productList);
            try {
                // 每隔一分鐘執(zhí)行一次
                Thread.sleep(1000 * 60);
                log.info("定時刷新特價商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 數(shù)據(jù)庫中查詢特價商品
     *
     * @return
     */
    public ListProduct> findProductsDB() {
        //ListProduct> productList = productMapper.selectListHot();
        ListProduct> productList = new ArrayList>();
        for (long i = 1; i = 100; i++) {
            Product product = new Product();
            product.setId((long) new Random().nextInt(1000));
            product.setPrice((double) i);
            product.setTitle("特價商品" + (i));
            productList.add(product);
        }
        return productList;
    }

}
package com.example.controller;

import com.example.entity.Product;
import com.example.service.ProductListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Auther: 長頸鹿
 * @Date: 2021/08/29/18:04
 * @Description:
 */
@RestController
public class ProductListController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductListService productListService;

    @GetMapping("/findProducts")
    public ListProduct> findProducts(int pageNo, int pageSize) {

        // 從那個集合去查詢

        String master_key = "product:hot:master:list";
        String slave_key = "product:hot:slave:list";

        String key = "product:hot:list";
        // 分頁的開始結(jié)束的換算
        if (pageNo = 0) pageNo = 1;
        int start = (pageNo - 1) * pageSize;
        // 計算分頁的結(jié)束頁
        int end = start + pageSize - 1;

        // 根據(jù)redis的api去處理分頁查詢對應(yīng)的結(jié)果
        try {

            ListProduct> productList = this.redisTemplate.opsForList().range(master_key, start, end);

//            ListProduct> productList = this.redisTemplate.opsForList().range(key, start, end);
            if (CollectionUtils.isEmpty(productList)) {
                // todo: 查詢數(shù)據(jù)庫,存在緩存擊穿的情況,大量的并發(fā)請求進來,可能把數(shù)據(jù)庫沖

                productList = this.redisTemplate.opsForList().range(slave_key, start, end);

//                productList = productListService.findProductsDB();
            }
            return productList;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

到此這篇關(guān)于基于Redis的List實現(xiàn)特價商品列表的文章就介紹到這了,更多相關(guān)redis list商品列表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python3操作redis實現(xiàn)List列表實例
  • Redis List列表的詳細介紹
  • redis redisson 集合的使用案例(RList、Rset、RMap)
  • Redis快速表、壓縮表和雙向鏈表(重點介紹quicklist)
  • redis 獲取 list 中的所有元素操作
  • 詳解Redis中的List類型
  • Redis list 類型學(xué)習(xí)筆記與總結(jié)
  • Redis教程(三):List數(shù)據(jù)類型

標簽:崇左 湖南 仙桃 衡水 湘潭 銅川 蘭州 黃山

巨人網(wǎng)絡(luò)通訊聲明:本文標題《基于Redis的List實現(xiàn)特價商品列表功能》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    天门市| 城口县| 增城市| 凯里市| 砚山县| 长宁县| 大余县| 贡山| 商丘市| 济阳县| 秀山| 重庆市| 兴仁县| 司法| 安义县| 门头沟区| 团风县| 浙江省| 株洲市| 桐柏县| 定结县| 马公市| 云林县| 上林县| 临泽县| 来宾市| 益阳市| 广宁县| 原平市| 怀安县| 蓬安县| 静乐县| 华宁县| 根河市| 岗巴县| 山东省| 桃源县| 叙永县| 桃江县| 绵阳市| 资阳市|