[Springboot]SpringCache + Redis实现数据缓存

前言

本文实现了SpringCache + Redis的集中式缓存,方便大家对学习了解缓存的使用。

本文实现:

  • SpringCache + Redis的组合
  • 通过配置文件实现了自定义key过期时间;key命名方式;value序列化方式

实现本文代码的前提:

  • 已有一个可以运行的Springboot项目,实现了简单的CRUD功能

步骤

在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

Generic
JCache (JSR-107)
EhCache 2.x
Hazelcast
Infinispan
Redis
Guava
Simple

我们所需要做的就是实现一个将缓存数据放在Redis的缓存机制。

  • 添加pom.xml依赖
    <!-- 缓存: spring cache -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-cache</artifactId>
	</dependency>

	<!-- 缓存: redis -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>

注意:- spring-boot-starter-data-redis和spring-boot-starter-redis的区别:https://blog.csdn.net/weixin_38521381/article/details/79397292

可以看出两个包并没有区别,但是当springBoot的版本为1.4.7 以上的时候,spring-boot-starter-redis 就空了。要想引入redis就只能选择有data的。

  • application.properties中加入redis连接设置(其它详细设置请查看参考网页)
# Redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.database=0
spring.redis.password=xxx
  • 新增KeyGeneratorCacheConfig.java(或者名为CacheConfig)文件

该文件完成三项设置:key过期时间;key命名方式;value序列化方式:JSON便于查看

package com.pricemonitor.pm_backend;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;

@Configuration
public class KeyGeneratorCacheConfig extends CachingConfigurerSupport {

    private final RedisTemplate redisTemplate;

    @Autowired
    public KeyGeneratorCacheConfig(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public CacheManager cacheManager() {
        // 设置key的序列化方式为String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化方式为JSON
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // 设置默认过期时间为600秒
        cacheManager.setDefaultExpiration(600);
        return cacheManager;
    }

    /**
     * key值为className+methodName+参数值列表
     * @return
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... args) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName()).append("#");
                sb.append(method.getName()).append("(");
                for (Object obj : args) {
                    if(obj != null) { // 在可选参数未给出时时,会出现null,此时需要跳过
                        sb.append(obj.toString()).append(",");
                    }
                }
                sb.append(")");
                return sb.toString();
            }
        };
    }
}

  • 在serviceImpl中加入@CacheConfig并且给给每个方法加入缓存(详细注解使用请查看参考网页)
@Service
@CacheConfig(cacheNames = "constant")
public class ConstantServiceImpl implements ConstantService {

    @Autowired
    private ConstantMapper constantMapper;

    @Cacheable
    @Override
    public List<Constant> alertMessage() {
        ConstantExample constantExample = new ConstantExample();
        ConstantExample.Criteria criteria = constantExample.createCriteria();
        criteria.andTypeEqualTo("alert");
        return constantMapper.selectByExample(constantExample);
    }

    @Cacheable
    @Override
    public List<Constant> noteMessage() {
        ConstantExample constantExample = new ConstantExample();
        ConstantExample.Criteria criteria = constantExample.createCriteria();
        criteria.andTypeEqualTo("note");
        return constantMapper.selectByExample(constantExample);
    }

    @Cacheable
    @Override
    public List<Constant> banner() {
        ConstantExample constantExample = new ConstantExample();
        ConstantExample.Criteria criteria = constantExample.createCriteria();
        criteria.andTypeEqualTo("banner");
        return constantMapper.selectByExample(constantExample);
    }
}

效果图

在这里插入图片描述

注意事项

  • 若直接修改数据库的表,并没有提供接口修改的字段,缓存就没法更新。所以这种字段加缓存需要尤其注意缓存的有效性,最好让其及时过期。或者给其实现增删改接口。

  • 大坑:在可选参数未给出时时,会出现null,此时在生成Key名的时候需要跳过。已在代码中修改

for (Object obj : args) {
    if(obj != null) { // 在可选参数未给出时时,会出现null,此时需要跳过
        sb.append(obj.toString()).append(",");
    }
}

参考

缓存入门:http://blog.didispace.com/springbootcache1/

Redis集中式缓存:http://blog.didispace.com/springbootcache2/

代码实现:(经典好用,有小bug):https://zhuanlan.zhihu.com/p/30540686

代码实现(可参考):https://www.jianshu.com/p/6ba2d2dbf36e

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值