基于Redis的List实现特价商品列表功能


Posted in Redis onAugust 30, 2021

 1、场景分析

淘宝京东的特价商品列表,

商品特点:

  • 商品有限,并发量非常的大。
  • 考虑分页

传统解决方案:数据库db,

但是在如此大的并发量的情况下,不可取。

一般会采用redis来处理。这些特价商品的数据不多,而且redis的list本身也支持分页。是天然处理这种列表的最佳选择解决方案。

2、分析

采用list数据,因为list数据结构有:lrange key 0 -1 可以进行数据的分页。

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 、具体实现

淘宝,京东的热门商品在双11的时候,可能有100多w需要搞活动:程序需要5分钟对特价商品进行刷新。

3.1 ProductListService类

  •  初始化的活动的商品信息100个(从数据库去查询)

@PostContrcut使用

  •  查询产品列表信息

换算的分页的起始位置和结束位置

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;

    // 数据热加载
    @PostConstruct
    public void initData(){
        log.info("启动定时加载特价商品到redis的list中...");
        new Thread(() -> runCourse()).start();
    }

    public void runCourse() {
        while (true) {
            // 从数据库中查询出特价商品
            List<Product> productList = this.findProductsDB();
            // 删除原来的特价商品
            this.redisTemplate.delete("product:hot:list");
            // 把特价商品添加到集合中
            this.redisTemplate.opsForList().leftPushAll("product:hot:list", productList);
            try {
                // 每隔一分钟执行一次
                Thread.sleep(1000 * 60);
                log.info("定时刷新特价商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 数据库中查询特价商品
     *
     * @return
     */
    public List<Product> findProductsDB() {
        //List<Product> productList = productMapper.selectListHot();
        List<Product> 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 商品的数据接口的定义和展示及分页

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 List<Product> findProducts(int pageNo, int pageSize) {

        // 从那个集合去查询
        String key = "product:hot:list";
        // 分页的开始结束的换算
        if (pageNo <= 0) pageNo = 1;
        int start = (pageNo - 1) * pageSize;
        // 计算分页的结束页
        int end = start + pageSize - 1;

        // 根据redis的api去处理分页查询对应的结果
        try {
            List<Product> productList = this.redisTemplate.opsForList().range(key, start, end);
            if (CollectionUtils.isEmpty(productList)) {
                //todo: 查询数据库,存在缓存击穿的情况,大量的并发请求进来,可能把数据库冲
                productList = productListService.findProductsDB();
            }
            return productList;

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

}

3.3 定时任务

@Configuration      // 主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 开启定时任务
public class SaticScheduleTask {
    // 添加定时任务
    @Scheduled(cron = "* 0/5 * * * ?")
    // 或直接指定时间间隔,例如:5秒
    // @Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

4、解决商品列表存在的缓存击穿问题

 4.1 如何引起的缓存击穿的情况

public void runCourse() {
        while (true) {
            // 从数据库中查询出特价商品
            List<Product> productList = this.findProductsDB();
            // 删除原来的特价商品
            this.redisTemplate.delete("product:hot:list");
            // 把特价商品添加到集合中 需要时间
            this.redisTemplate.opsForList().leftPushAll("product:hot:list", productList);
            try {
                // 每隔一分钟执行一遍
                Thread.sleep(1000 * 60);
                log.info("定时刷新特价商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

出现原因:

  • 特价商品的数据更换需要时间,刚好特价商品还没有放入到redis缓存中。
  • 查询特价商品的并发量非常大,可能程序还正在写入特价商品到缓存中,这时查询缓存根本没有数据,就会直接冲入数据库中去查询特价商品。可能造成数据库冲垮。这个就叫做:缓存击穿

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;

    // 数据热加载
    @PostConstruct
    public void initData(){
        log.info("启动定时加载特价商品到redis的list中...");
        new Thread(() -> runCourse()).start();
    }

    public void runCourse() {
        while (true) {
            // 从数据库中查询出特价商品
            List<Product> 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 {
                // 每隔一分钟执行一次
                Thread.sleep(1000 * 60);
                log.info("定时刷新特价商品....");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 数据库中查询特价商品
     *
     * @return
     */
    public List<Product> findProductsDB() {
        //List<Product> productList = productMapper.selectListHot();
        List<Product> 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 List<Product> findProducts(int pageNo, int pageSize) {

        // 从那个集合去查询

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

        String key = "product:hot:list";
        // 分页的开始结束的换算
        if (pageNo <= 0) pageNo = 1;
        int start = (pageNo - 1) * pageSize;
        // 计算分页的结束页
        int end = start + pageSize - 1;

        // 根据redis的api去处理分页查询对应的结果
        try {

            List<Product> productList = this.redisTemplate.opsForList().range(master_key, start, end);

//            List<Product> productList = this.redisTemplate.opsForList().range(key, start, end);
            if (CollectionUtils.isEmpty(productList)) {
                // todo: 查询数据库,存在缓存击穿的情况,大量的并发请求进来,可能把数据库冲

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

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

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

}

到此这篇关于基于Redis的List实现特价商品列表的文章就介绍到这了,更多相关redis list商品列表内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Redis 相关文章推荐
Redis如何一键部署脚本
Apr 12 Redis
Redis安装启动及常见数据类型
Apr 14 Redis
Redis持久化与主从复制的实践
Apr 27 Redis
Redis 配置文件重要属性的具体使用
May 20 Redis
详解Redis复制原理
Jun 04 Redis
Redis三种集群模式详解
Oct 05 Redis
Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题
Feb 12 Redis
解决linux下redis数据库overcommit_memory问题
Feb 24 Redis
解决redis批量删除key值的问题
Mar 23 Redis
Redis实现订单过期删除的方法步骤
Jun 05 Redis
利用Redis实现点赞功能的示例代码
Jun 28 Redis
基于Redission的分布式锁实战
Aug 14 Redis
Redis 常见使用场景
Aug 30 #Redis
Redis入门教程详解
Redis如何实现分布式锁
Aug 23 #Redis
Redisson实现Redis分布式锁的几种方式
Redis分布式锁Redlock的实现
Aug 07 #Redis
关于redisson缓存序列化几枚大坑说明
Aug 04 #Redis
Redis Cluster 集群搭建你会吗
Aug 04 #Redis
You might like
php的hash算法介绍
2014/02/13 PHP
php使用mysqli和pdo扩展,测试对比mysql数据库的执行效率完整示例
2019/05/09 PHP
jQuery 表单验证插件formValidation实现个性化错误提示
2009/06/23 Javascript
jquery 学习之二 属性(html()与html(val))
2010/11/25 Javascript
多种方式实现JS调用后台方法进行数据交互
2013/08/20 Javascript
Javascript 颜色渐变效果的实现代码
2013/10/01 Javascript
JavaScript学习笔记(三):JavaScript也有入口Main函数
2015/09/12 Javascript
AngualrJS中的Directive制作一个菜单
2016/01/26 Javascript
jQuery实现横向带缓冲的水平运动效果(附demo源码下载)
2016/01/29 Javascript
jquery插件jquery.LightBox.js实现点击放大图片并左右点击切换效果(附demo源码下载)
2016/02/25 Javascript
vue,angular,avalon这三种MVVM框架优缺点
2016/04/27 Javascript
js数组操作方法总结(必看篇)
2016/11/22 Javascript
AngularJS实现ajax请求的方法
2016/11/22 Javascript
JS按钮闪烁功能的实现代码
2017/07/21 Javascript
学习jQuery中的noConflict()用法
2018/09/28 jQuery
koa大型web项目中使用路由装饰器的方法示例
2019/04/02 Javascript
Vue项目总结之webpack常规打包优化方案
2019/06/06 Javascript
layui加载表格,绑定新增,编辑删除,查看按钮事件的例子
2019/09/06 Javascript
JS面向对象编程——ES6 中class的继承用法详解
2020/03/03 Javascript
vue使用swiper实现左右滑动切换图片
2020/10/16 Javascript
react antd表格中渲染一张或多张图片的实例
2020/10/28 Javascript
tornado框架blog模块分析与使用
2013/11/21 Python
Python写的Discuz7.2版faq.php注入漏洞工具
2014/08/06 Python
深入理解Python中的内置常量
2017/05/20 Python
matplotlib jupyter notebook 图像可视化 plt show操作
2020/04/24 Python
django Layui界面点击弹出对话框并请求逻辑生成分页的动态表格实例
2020/05/12 Python
全球性的众包图形设计市场:DesignCrowd
2021/02/02 全球购物
房地产销售大学生自我评价分享
2013/11/11 职场文书
门卫岗位职责
2013/11/15 职场文书
运动会入场解说词
2014/02/07 职场文书
支行行长竞聘报告
2014/11/06 职场文书
夫妻忠诚协议书范本
2014/11/17 职场文书
廉洁自律承诺书范文
2015/04/28 职场文书
盗窃案辩护词
2015/05/21 职场文书
手把手教你制定暑期学习计划,让你度过充实的暑假
2019/08/22 职场文书
解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题
2021/07/01 Java/Android