实战SSM_O2O商铺_46【Redis缓存】头条信息+商铺目录Service层加入缓存

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 实战SSM_O2O商铺_46【Redis缓存】头条信息+商铺目录Service层加入缓存

概述


根据数据的特点,不经常变动的数据 即时性要求没有那么高的读数据 为了减轻DB压力,我们可以将数据放到缓存中。


按照规划,目前我们需要将区域信息、商铺分类信息和头条信息放入到redis中。


实战SSM_O2O商铺_45【Redis缓存】配置Redis在Service层加入缓存中我们集成了Redis的配置,并使用AreaService来测试了配置的正确性。 接下来我们继续将商铺分类信息和头条信息放入到redis中。


HeadLineServiceImpl的改造

代码

思路:根据mapper中不同的查询条件,在service层缓存不同的KEY,方便使用。

package com.artisan.o2o.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.artisan.o2o.cache.JedisUtil;
import com.artisan.o2o.dao.HeadLineDao;
import com.artisan.o2o.entity.HeadLine;
import com.artisan.o2o.service.HeadLineService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class HeadLineServiceImpl implements HeadLineService {
  private static final Logger logger = LoggerFactory.getLogger(HeadLineServiceImpl.class);
  @Autowired
  HeadLineDao headLineDao;
  @Autowired
  private JedisUtil.Strings jedisStrings;
  @Autowired
  private JedisUtil.Keys jedisKeys;
  @Override
  public List<HeadLine> queryHeadLineList(HeadLine headLineConditon) {
    List<HeadLine> headLineList = new ArrayList<HeadLine>();
    // 定义Key
    String key = "headline";
    // 定义jackson数据转换操作类
    ObjectMapper mapper = new ObjectMapper();
    // 根据mapper中的查询条件 拼装key
    // 根据不同的条件缓存不同的key值 这里有3种缓存 headline_0 headline_1 和 headline 方便管理员权限操作
    if (headLineConditon != null && headLineConditon.getEnableStatus() != null) {
      key = key + "_" + headLineConditon.getEnableStatus();
    }
    // 如果不存在,从数据库中获取数据,然后写入redis
    if(!jedisKeys.exists(key)){
      try {
        // 从DB中获取数据
        headLineList = headLineDao.selectHeadLineList(headLineConditon);
        // 将相关的实体类集合转换成string,存入redis里面对应的key中
        String jsonString = mapper.writeValueAsString(headLineList);
        jedisStrings.set(key, jsonString);
      } catch (JsonProcessingException e) {
        e.printStackTrace();
        logger.error("实体类集合转换string存入redis异常{}", e.getMessage());
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("其他异常{}", e.getMessage());
      }
    } else {
      // 否则直接从redis中获取
      try {
        // 若存在,则直接从redis里面取出相应数据
        String jsonString = jedisStrings.get(key);
        // 指定要将string转换成的集合类型
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, HeadLine.class);
        // 将相关key对应的value里的的string转换成java对象的实体类集合
        headLineList = mapper.readValue(jsonString, javaType);
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("异常{}", e.getMessage());
      }
    }
    return headLineList;
  }
}


单元测试

tb_head_line数据


20180816212346849.png


package com.artisan.o2o.service;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.artisan.o2o.BaseTest;
import com.artisan.o2o.entity.HeadLine;
public class HeadLineServiceTest extends BaseTest {
  @Autowired
  private HeadLineService headLineService;
  @Test
  public void testQueryHeadLineList() {
    HeadLine headLineConditon = new HeadLine();
    // 状态 0 不可用 1 可用
    headLineConditon.setEnableStatus(0);
    // 查询不可用的头条信息
    List<HeadLine> headLineList = headLineService.queryHeadLineList(headLineConditon);
    for (HeadLine headLine : headLineList) {
      System.out.println("0<<<<" + headLine);
    }
    // 查询可用的头条信息
    headLineConditon.setEnableStatus(1);
    headLineList = headLineService.queryHeadLineList(headLineConditon);
    for (HeadLine headLine : headLineList) {
      System.out.println("**------>" + headLine);
    }
    // 再次查询 状态为0 和 1的头条信息 ,确保从缓存中取数据
    // 查询不可用的头条信息
    headLineConditon.setEnableStatus(0);
    headLineList = headLineService.queryHeadLineList(headLineConditon);
    for (HeadLine headLine : headLineList) {
      System.out.println("0>>>>" + headLine);
    }
    // 查询可用的头条信息
    headLineConditon.setEnableStatus(1);
    headLineList = headLineService.queryHeadLineList(headLineConditon);
    for (HeadLine headLine : headLineList) {
      System.out.println("||------>" + headLine);
    }
  }
}

启动redis服务端,确保redis中无对应的数据,加入断点逐步调测观察。 单元测试后查看Redis中的数据

127.0.0.1:6379> get headline_0
"[]"
127.0.0.1:6379> get headline_1
"[{\"lineId\":6,\"lineName\":\"\xe8\xb4\xad\xe7\x89\xa9\",\"lineLink\":\"xxx\",\"lineImg\":\"\\\\upload\\\\item\\\\headtitle\\\\2018072520315746624.jpg\",\"priority\":99,\"enableStatus\":1,\"createTime\":null,\"lastEditTime\":null},{\"lineId\":2,\"lineName\":\"\xe5\xae\xb6\xe5\x85\xb7\",\"lineLink\":\"x\",\"lineImg\":\"\\\\upload\\\\item\\\\headtitle\\\\2018072520371786788.jpg\",\"priority\":98,\"enableStatus\":1,\"createTime\":null,\"lastEditTime\":null},{\"lineId\":3,\"lineName\":\"\xe5\x81\xa5\xe8\xba\xab\",\"lineLink\":\"xx\",\"lineImg\":\"\\\\upload\\\\item\\\\headtitle\\\\2018072520393452772.jpg\",\"priority\":97,\"enableStatus\":1,\"createTime\":null,\"lastEditTime\":null},{\"lineId\":4,\"lineName\":\"\xe7\xbe\x8e\xe5\xae\xb9\",\"lineLink\":\"aa\",\"lineImg\":\"\\\\upload\\\\item\\\\headtitle\\\\2018072520400198256.jpg\",\"priority\":96,\"enableStatus\":1,\"createTime\":null,\"lastEditTime\":null}]"
127.0.0.1:6379>


符合预期,测试通过。


ShopCategoryServiceImpl的改造

思路:根据mapper中不同的查询条件,在service层缓存不同的KEY,方便使用。


代码

package com.artisan.o2o.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.artisan.o2o.cache.JedisUtil;
import com.artisan.o2o.dao.ShopCategoryDao;
import com.artisan.o2o.entity.ShopCategory;
import com.artisan.o2o.service.ShopCategoryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {
  private static final Logger logger = LoggerFactory.getLogger(ShopCategoryServiceImpl.class);
  @Autowired
  private ShopCategoryDao shopCategoryDao;
  @Autowired
  private JedisUtil.Keys jedisKeys;
  @Autowired
  private JedisUtil.Strings jedisStrings;
  @Override
  public List<ShopCategory> getShopCategoryList(ShopCategory shopCategory) {
    List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
    // 定义redis中key
    String key = "shopcategory";
    // 定义jackson数据转换操作类
    ObjectMapper mapper = new ObjectMapper();
    // 根据mapper中的查询条件,拼装shopcategory的key
    if (shopCategory == null) {
      // 查询条件为空,列出所有的首页大类,即parentId为空的店铺类别
      key = key + "_allfirstlevelshopcategory";
    } else if (shopCategory != null && shopCategory.getParent() != null && shopCategory.getParent().getShopCategoryId() != null) {
      // 列出某个parentId下面的所有子类
      key = key + "_parent" + shopCategory.getParent().getShopCategoryId();
    } else if (shopCategory != null) {
      // 列出所有的子类,不管属于哪个类
      key = key + "_allsecondlevelshopcategory";
    }
    // 如果缓存中不出在则从DB中查询并缓存到redis中
    if (!jedisKeys.exists(key)) {
      try {
        // 从DB中加载
        shopCategoryList = shopCategoryDao.queryShopCategoryList(shopCategory);
        // 将相关的实体类集合转换成string,存入redis里面对应的key中
        String jsonString = mapper.writeValueAsString(shopCategoryList);
        jedisStrings.set(key, jsonString);
      } catch (JsonProcessingException e) {
        e.printStackTrace();
        logger.error("实体类集合转换string存入redis异常{}", e.getMessage());
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("其他异常{}", e.getMessage());
      }
    } else {
      // 否则直接从redis中获取
      try {
        String jsonString = jedisStrings.get(key);
        // 指定要将string转换成的集合类型
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, ShopCategory.class);
        // 将相关key对应的value里的的string转换成java对象的实体类集合
        shopCategoryList = mapper.readValue(jsonString, javaType);
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("异常{}", e.getMessage());
      }
    }
    return shopCategoryList;
  }
}


单元测试

tb_shop_category 数据


20180816220152825.png

package com.artisan.o2o.service;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.artisan.o2o.BaseTest;
import com.artisan.o2o.entity.ShopCategory;
public class ShopServiceCategoryTest extends BaseTest {
  @Autowired
  ShopCategoryService shopCategoryService;
  @Test
  public void testQueryShopCategory() {
    List<ShopCategory> shopCategories;
    // 查询 ShopCategory为null的情况,即查询parent_id is null
    shopCategories = shopCategoryService.getShopCategoryList(null);
    for (ShopCategory shopCategory2 : shopCategories) {
      System.out.println("-----||" + shopCategory2);
    }
    // 查询 ShopCategory不为空的情况
    ShopCategory shopCategory = new ShopCategory();
    shopCategories = shopCategoryService.getShopCategoryList(shopCategory);
    for (ShopCategory shopCategory2 : shopCategories) {
      System.out.println("----->>" + shopCategory2);
    }
    // 查询对应父类下的目录
    ShopCategory parent = new ShopCategory();
    ShopCategory child = new ShopCategory();
    parent.setShopCategoryId(1L);
    child.setParent(parent);
    shopCategories = shopCategoryService.getShopCategoryList(child);
    for (ShopCategory shopCategory2 : shopCategories) {
      System.out.println("-----**" + shopCategory2);
    }
  }
}


运行两次,查看数据,符合预期


20180816220249784.png


Github地址


代码地址: https://github.com/yangshangwei/o2o

相关文章
|
10天前
|
存储 NoSQL 前端开发
Redis专题-实战篇一-基于Session和Redis实现登录业务
本项目基于SpringBoot实现黑马点评系统,涵盖Session与Redis两种登录方案。通过验证码登录、用户信息存储、拦截器校验等流程,解决集群环境下Session不共享问题,采用Redis替代Session实现数据共享与自动续期,提升系统可扩展性与安全性。
83 3
Redis专题-实战篇一-基于Session和Redis实现登录业务
|
10天前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
73 1
Redis专题-实战篇二-商户查询缓存
|
2月前
|
缓存 开发者
如何在Performance面板中查看缓存相关信息?
如何在Performance面板中查看缓存相关信息?
201 56
|
3月前
|
缓存 监控 NoSQL
Redis 实操要点:Java 最新技术栈的实战解析
本文介绍了基于Spring Boot 3、Redis 7和Lettuce客户端的Redis高级应用实践。内容包括:1)现代Java项目集成Redis的配置方法;2)使用Redisson实现分布式可重入锁与公平锁;3)缓存模式解决方案,包括布隆过滤器防穿透和随机过期时间防雪崩;4)Redis数据结构的高级应用,如HyperLogLog统计UV和GeoHash处理地理位置。文章提供了详细的代码示例,涵盖Redis在分布式系统中的核心应用场景,特别适合需要处理高并发、分布式锁等问题的开发场景。
266 41
|
2月前
|
存储 缓存 安全
Go语言实战案例-LRU缓存机制模拟
本文介绍了使用Go语言实现LRU缓存机制的方法。LRU(最近最少使用)是一种常见缓存淘汰策略,当缓存满时,优先删除最近最少使用的数据。实现中使用哈希表和双向链表结合的方式,确保Get和Put操作均在O(1)时间内完成。适用于Web缓存、数据库查询优化等场景。
|
3月前
|
缓存 NoSQL 算法
高并发秒杀系统实战(Redis+Lua分布式锁防超卖与库存扣减优化)
秒杀系统面临瞬时高并发、资源竞争和数据一致性挑战。传统方案如数据库锁或应用层锁存在性能瓶颈或分布式问题,而基于Redis的分布式锁与Lua脚本原子操作成为高效解决方案。通过Redis的`SETNX`实现分布式锁,结合Lua脚本完成库存扣减,确保操作原子性并大幅提升性能(QPS从120提升至8,200)。此外,分段库存策略、多级限流及服务降级机制进一步优化系统稳定性。最佳实践包括分层防控、黄金扣减法则与容灾设计,强调根据业务特性灵活组合技术手段以应对高并发场景。
1026 7
|
3月前
|
机器学习/深度学习 存储 NoSQL
基于 Flink + Redis 的实时特征工程实战:电商场景动态分桶计数实现
本文介绍了基于 Flink 与 Redis 构建的电商场景下实时特征工程解决方案,重点实现动态分桶计数等复杂特征计算。通过流处理引擎 Flink 实时加工用户行为数据,结合 Redis 高性能存储,满足推荐系统毫秒级特征更新需求。技术架构涵盖状态管理、窗口计算、Redis 数据模型设计及特征服务集成,有效提升模型预测效果与系统吞吐能力。
340 2
|
存储 缓存 NoSQL
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
快速学习 Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
|
缓存 NoSQL 安全
6.0Spring Boot 2.0实战 Redis 分布式缓存6.0|学习笔记
快速学习6.0Spring Boot 2.0实战 Redis 分布式缓存6.0。
467 0
6.0Spring Boot 2.0实战 Redis 分布式缓存6.0|学习笔记
|
缓存 NoSQL Redis
首页数据显示-添加 redis 缓存(3)| 学习笔记
快速学习 首页数据显示-添加 redis 缓存(3)
220 0
首页数据显示-添加 redis 缓存(3)| 学习笔记