SpringBoot——自定义Redis缓存Cache

SpringBoot自带Cache存在问题:

1.生成Key过于简单,容易冲突 默认为cacheNames + ":" + Key2.无法设置过期时间,默认时间是永久3.配置序列化方式,默认是JDKSerializable,可能造成乱码

自定义Cache分三个步骤:

1.自定义KeyGenerator2.自定义cacheManager 设置缓存过期时间3.自定义序列化方式 JackSon

1.修改pom.xml文件

org.springframework.boot
  spring-boot-starter-data-redis

  org.springframework.boot
  spring-boot-starter-cache

2.添加RedisConfig.java配置

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @EnableCaching 开启SpringBoot的Cache缓存
 *
 * */
@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){

        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        return template;
    }

    /**
     * 自定义key值格式
     *
     * */
    @Bean
    public KeyGenerator simpleKeyGenerator(){
        return (o, method, objects) -> {
          StringBuilder builder = new StringBuilder();
          //获取类名称
          builder.append(o.getClass().getSimpleName());
          builder.append(".");
          //获取方法名称
          builder.append(method.getName());
          builder.append("[");
          //遍历方法参数
          for (Object obj : objects){
              builder.append(obj.toString());
          }
          builder.append("]");
          return builder.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
        return new RedisCacheManager(
                RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory),
                //默认Cache缓存的超时配置
                this.getRedisCacheConfigurationWithTtl(30),
                //自定义Cache缓存Key的超时配置
                this.getRedisCacheConfigurationMap()
        );
    }

    /**
     * 配置自定义Cache缓存Key的超时规则
     *
     * */
    public Map getRedisCacheConfigurationMap(){
        Map redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("UserInfoCacheList", this.getRedisCacheConfigurationWithTtl(20));
//        redisCacheConfigurationMap.put("UserInfoCacheAnother", this.getRedisCacheConfigurationWithTtl(30));
        return redisCacheConfigurationMap;
    }

    /**
     * 自定义Cache缓存超时规则
     *
     * */
    public RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
                //修改Key的命名规则 默认:cacheName + ":"
//                .computePrefixWith(cacheName -> cacheName.concat(":"))
//                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                    .SerializationPair
                    .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));
        return redisCacheConfiguration;
    }
}

3.添加Service配置

备注:

只有最后一个是自定义的 前面的是springboot自带的方法

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.theng.shopuser.entity.UserInfo;
import com.theng.shopuser.entity.dto.UserInfoDto;
import com.theng.shopuser.mapper.UserInfoMapper;
import com.theng.shopuser.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 *
 *  服务实现类
 *
 *
 * @author tianheng
 * @since 2020-02-09
 */
@Service
@CacheConfig(cacheNames = "userInfoCache")
public class UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;/**
     * 获取缓存中的UserInfo
     * #p0: 对应方法参数 0表示第一个参数
     *
     * */
    @Override
    @Nullable
    @Cacheable(key = "#p0", unless = "#result == null")
    public UserInfo findUserInfoCache(String code){

        return userInfoMapper.findUserInfoByCode(code);
    }

    /**
     * 向缓存中插入UserInfo
     * return: 必须要有返回值 否则无法保存到缓存中
     *
     * */
    @Override
    @CachePut(key = "#p0.userCode")
    public UserInfo insertUserInfoCache(UserInfo userInfo){
        return null;
    }

    /**
     * 向缓存中插入UserInfo
     * return: 必须要有返回值 否则无法保存到缓存中
     *
     * */
    @Override
    @CachePut(key = "#p0.userCode")
    public UserInfo updateUserInfoCache(UserInfo userInfo){
        return null;
    }

    /**
     * 删除cacheNames = "userInfoCache",key值为指定值的缓存
     *
     * */
    @Override
    @CacheEvict(key = "#p0")
    public void deleteUserInfoCache(String userCode){

    }

    /**
     * 清除cacheNames = "userInfoCache"下的所有缓存
     * 如果失败了,则不会清除
     *
     * */
    @Override
    @CacheEvict(allEntries = true)
    public void deleteAllUserInfoCache(){

    }

    @Nullable
    @Cacheable(value = "UserInfoCacheList", keyGenerator = "simpleKeyGenerator")
    public UserInfo customUserInfoCache(){

        return null;
    }
}

4.修改controller.java

import com.theng.shopuser.bean.UserSessionBean;
import com.theng.shopuser.entity.UserInfo;
import com.theng.shopuser.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user-info")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    //测试
    @GetMapping("/list2")
    public Object getList2() {

        UserInfo userInfo = userInfoService.findUserInfoByCode("YH006");

        return "success";
    }

    @GetMapping("/list3")
    public Object getList3() {
        UserInfo userInfo = userInfoService.customUserInfoCache();
        return "success";
    }
}

5.修改pom.xml文件

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    password:

6.输出结果

自定义

SpringBoot------自定义Redis缓存Cache

Original: https://www.cnblogs.com/tianhengblogs/p/15322852.html
Author: 玉天恒
Title: SpringBoot——自定义Redis缓存Cache

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/529132/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 这几天的杂学

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Linux 2023年6月7日
    082
  • VIM快捷键全集

    VIM快捷键大法 vim是我最喜欢的编辑器,也是linux下第二强大的编辑器。 虽然emacs是公认的世界第一,我认为使用emacs并没有使用vi进行编辑来得高效。 如果是初学vi…

    Linux 2023年6月7日
    082
  • Redis 常用五种数据类型编码

    1.String 1.1 常用命令 (1)设置值 set key value [ex seconds] [px milliseconds] [nx|xx] set命令有几个选项: …

    Linux 2023年5月28日
    089
  • K8S的apiVersion版本详解

    1. 背景 Kubernetes的官方文档中并没有对apiVersion的详细解释,而且因为K8S本身版本也在快速迭代,有些资源在低版本还在beta阶段,到了高版本就变成了stab…

    Linux 2023年6月14日
    068
  • 正则表达式测试

    本博客所有文章仅用于学习、研究和交流目的,欢迎非商业性质转载。 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高,不足和错误之处在所难免,希望大家能够批评指出。 博主…

    Linux 2023年6月13日
    073
  • centos7 安装MariaDB 10.6

    镜像下载、域名解析、时间同步请点击阿里云开源镜像站 背景 centos7使用yum install mariadb-server命令安装的默认版本是5.5的,这是因为系统默认源只有…

    Linux 2023年5月27日
    0346
  • 数据库性能优化八大方案,你知道几个

    前言 毫不夸张的说咱们后端工程师,无论在哪家公司,呆在哪个团队,做哪个系统,遇到的第一个让人头疼的问题绝对是数据库性能问题。 如果我们有一套成熟的方法论,能让大家快速、准确的去选择…

    Linux 2023年6月13日
    065
  • 搭建一个完整的K8S集群——-基于CentOS 8系统

    创建三个centos节点: 192.168.5.141 k8s-master 192.168.5.142 k8s-nnode1 192.168.5.143 k8s-nnode2 查…

    Linux 2023年6月7日
    074
  • apt-get指令关于卸载软件的各种用法

    一、 apt-get remove packagename 该命令将移除与 packagename相关联的所有二进制文件,但是不会移除与之相关联的配置文件或数据文件(configu…

    Linux 2023年5月27日
    0128
  • python中的反射

    python反射简介 所谓反射是指通过字符串的方式获取对象,然后执行对象的属性或方法。在python中一切皆对象,因此我们可以对一切事物进行发射。 关于反射python为我们提供了…

    Linux 2023年6月7日
    084
  • 快速构建Web应用,从零学习React后台项目模版

    想要快速构建实际应用,离不开一个好的应用模版,React作为大厂出品工具,有着稳定性和可维护性的保障,同时可以使用相关的全套全家桶(React + React-router + A…

    Linux 2023年5月27日
    085
  • ArrayList中的遍历删除

    例如我们有下列数据,要求遍历列表并删除所有偶数。 List myList = new ArrayList<>(Arrays.toList(new Integer[]{2…

    Linux 2023年6月13日
    078
  • Linux快速入门(七)效率工具(Vim)

    Vim编辑器 所有的 Linux系统都会内建一个 Vi文本编辑器,而 Vim是从 Vi发展出来的一个高度可配置的文本编辑器,旨在高效的创建和更改任何类型的文本,它还可以根据文件的扩…

    Linux 2023年6月6日
    089
  • tomcat

    tomcat 一.简介 二.部署tomcat 一.简介 Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场…

    Linux 2023年6月7日
    093
  • vim编辑器

    vim 编辑器 2018 年12 月12 日 22:15 常用操作 命令模式(初始模式) 输入模式(i 进入) 底行命令模式(:进入) / 往下搜索 ? 往上搜索 n 搜索下一个 …

    Linux 2023年6月13日
    0100
  • Redis 经验谈

    新浪作为全世界最大的Redis用户,在开发和运维方面有非常多的经验。本文作者来自新浪,希望能为业界提供一些亲身经历,让大家少走弯路。 使用初衷 从2010年上半年起,我们就开始尝试…

    Linux 2023年5月28日
    084
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球