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

简介: 实战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

相关文章
|
3月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
|
4月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
245 1
Redis专题-实战篇二-商户查询缓存
|
3月前
|
缓存 运维 监控
Redis 7.0 高性能缓存架构设计与优化
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Redis 7.0高性能缓存架构,探索函数化编程、多层缓存、集群优化与分片消息系统,用代码在二进制星河中谱写极客诗篇。
|
4月前
|
缓存 NoSQL 关系型数据库
Redis缓存和分布式锁
Redis 是一种高性能的键值存储系统,广泛用于缓存、消息队列和内存数据库。其典型应用包括缓解关系型数据库压力,通过缓存热点数据提高查询效率,支持高并发访问。此外,Redis 还可用于实现分布式锁,解决分布式系统中的资源竞争问题。文章还探讨了缓存的更新策略、缓存穿透与雪崩的解决方案,以及 Redlock 算法等关键技术。
|
8月前
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
8月前
|
缓存 NoSQL Java
Redis+Caffeine构建高性能二级缓存
大家好,我是摘星。今天为大家带来的是Redis+Caffeine构建高性能二级缓存,废话不多说直接开始~
1216 0
|
8月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
287 32
|
8月前
|
缓存 NoSQL Java
Redis:现代服务端开发的缓存基石与电商实践-优雅草卓伊凡
Redis:现代服务端开发的缓存基石与电商实践-优雅草卓伊凡
234 5
Redis:现代服务端开发的缓存基石与电商实践-优雅草卓伊凡
|
10月前
|
缓存 NoSQL Java
Redis应用—8.相关的缓存框架
本文介绍了Ehcache和Guava Cache两个缓存框架及其使用方法,以及如何自定义缓存。主要内容包括:Ehcache缓存框架、Guava Cache缓存框架、自定义缓存。总结:Ehcache适合用作本地缓存或与Redis结合使用,Guava Cache则提供了更灵活的缓存管理和更高的并发性能。自定义缓存可以根据具体需求选择不同的数据结构和引用类型来实现特定的缓存策略。
659 16
Redis应用—8.相关的缓存框架
|
存储 缓存 NoSQL
解决Redis缓存数据类型丢失问题
解决Redis缓存数据类型丢失问题
514 85