前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Springboot]SpringCache + Redis实现数据缓存

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

作者头像
Rude3Knife的公众号
发布2019-08-07 11:29:36
1.2K0
发布2019-08-07 11:29:36
举报
文章被收录于专栏:后端技术漫谈后端技术漫谈

前言

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

本文实现:

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

实现本文代码的前提:

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

步骤

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

代码语言:javascript
复制
Generic
JCache (JSR-107)
EhCache 2.x
Hazelcast
Infinispan
Redis
Guava
Simple

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

  • 添加pom.xml依赖
代码语言:javascript
复制
<!-- 缓存: 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连接设置(其它详细设置请查看参考网页)
代码语言:javascript
复制
# 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便于查看

代码语言:javascript
复制
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并且给给每个方法加入缓存(详细注解使用请查看参考网页)
代码语言:javascript
复制
@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名的时候需要跳过。已在代码中修改
代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-12-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 后端技术漫谈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 步骤
  • 效果图
  • 注意事项
  • 参考
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档