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)

大家都在看

  • 翻车!误删/usr/lib/引发的血案,从棺材边成功抢救的过程分享。

    写在开篇 血案:本地开发机是CentOS 7,本想删除在/usr/lib/下的一个软链,如:/usr/lib/xxx。当正想删除时,突然被别的事情打扰了一下,回过神之后莫名奇妙的执…

    Linux 2023年6月7日
    0101
  • python爬虫配置IP代理池(ProxyPool)

    关注我的公众号【靠谱杨的挨踢生活】回复 ProxyPool可以免费获取网盘链接。也可自行搜索下载:https://github.com/Python3WebSpider/Proxy…

    Linux 2023年6月14日
    0105
  • VMware 和 Linux 的安装

    常见的虚拟机软件有 VMware Workstation(简称 VMware)、VirtualBox、Microsoft Virtual PC 等,本文以 VMware 为例来讲解…

    Linux 2023年5月27日
    083
  • QT和Java的跨平台

    大家基本上都知道QT是跨平台的,Java也是跨平台的,那咱们今天就来聊聊他们两个: 相同点:都是跨平台 不同点:Java 的运行是建立在虚拟机上的,在虚拟机上 一次编译到处运行,但…

    Linux 2023年6月13日
    097
  • tomcat

    1. tomcat简介 2. tomcat的部署 2.1 java环境的安装 2.2 tomcat部署 2.3 访问Host Manager界面 2.4 访问Server Stat…

    Linux 2023年6月13日
    0118
  • html2canvas生成并下载图片

    html <div id="downChart"> div> jq new html2canvas(document.getElementBy…

    Linux 2023年6月7日
    085
  • 聊聊支付流程的设计与实现逻辑

    新手打怵老手头疼的业务; 一、业务背景 通常在业务体系中,都会或多或少的涉及到支付相关的功能;对于一些经验欠缺同学来说,最紧张的就是面对这类支付结算的逻辑,因为流程中的任何细节问题…

    Linux 2023年6月14日
    083
  • Rabbitmq安装与部署

    安装包otp_src_22.3.tar.gz,下载到部署服务器tar -zxvf解压 mv otp_src_22.3 ./erlang变更文件夹名字 可能需要安装的依赖包 yum …

    Linux 2023年5月27日
    097
  • SQL52 获取employees中的first_name

    本题链接表结构如下所示(内容不完整):额外的要求是按照first_name最后两个字母升序进行输出。这里需要用到MySQL的字符串处理函数RIGHT。RIGHT函数的语法如下所示:…

    Linux 2023年6月13日
    0117
  • Java50个关键字之abstract

    abstract abstract 可以出现的位置: 修饰方法 修饰类 修饰类 一个类被 abstract修饰,那么该类就叫做 &#x62BD;&#x8C61;&a…

    Linux 2023年6月7日
    091
  • X86 assembly guide

    This guide describes the basics of 32-bit x86 assembly language programming, covering a sm…

    Linux 2023年6月7日
    0141
  • Linux 查看运行中进程的 umask

    线上某台虚机因为故障重装了系统(基线 CentOS 6.9 内核 2.6.x),重新部署了应用。这个应用会生成一个文件,到NFS挂载目录。 而这个 NFS 挂载目录是一个 FTP …

    Linux 2023年5月27日
    0151
  • Redis内存满了怎么办

    Redis是基于内存的key-value数据库,因为系统的内存大小有限,所以我们在使用Redis的时候可以配置Redis能使用的最大的内存大小。 1、通过配置文件配置 通过在Red…

    Linux 2023年5月28日
    070
  • Linux基础和命令

    Linux的哲学思想 优势 一切都是一个文件。(包括硬件,文本,二进制,源代 码) 系统中拥有小型,单一用途的程序。(一个程序只负责 做好自己的本职工作) 当遇到复杂任务,通过不同…

    Linux 2023年6月6日
    091
  • 有道词典翻译功能数字有时无法翻译出来解决方案

    阅文时长 | 0.03分钟字数统计 | 62.4字符主要内容 | 1、引言&背景 2、解决方案 3、声明与参考资料『有道词典翻译功能数字有时无法翻译出来解决方案』 编写人 …

    Linux 2023年6月14日
    0188
  • 门罗币XMR最新挖矿算法RandomX设计原理

    Randomx算法-门罗币XMR的挖矿新算法 RandomX算法设计目标是抗ASIC+降低GPU优势。 Monero门罗币XMR计划于2019年的10月份启用最新的RandomX …

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