当前位置: 代码网 > it编程>编程语言>Java > redis在springboot中做缓存操作的两种方法应用实例

redis在springboot中做缓存操作的两种方法应用实例

2025年09月24日 Java 我要评论
众所周知,redis是一个高性能的键值对存储数据库,在现在的程序构建时,当数据量较大时或数据重复利用时常常利用缓存技术来减少时间消耗和资源浪费,本文就是介绍在springboot中如何利用redis做

众所周知,redis是一个高性能的键值对存储数据库,在现在的程序构建时,当数据量较大时或数据重复利用时常常利用缓存技术来减少时间消耗和资源浪费,本文就是介绍在springboot中如何利用redis做缓存

一.进行redis的安装与开启(简略)

在windows系统或linux系统都可

默认已安装完redis

二.进行依赖引入和配置文件搭建

依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-cache</artifactid>
</dependency>

配置文件(application.properties)

spring.redis.host=(你redis主机的ip地址)
spring.redis.port=6379
spring.redis.password=
# 可选连接池配置
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

三.构建config以及加注解

在主启动类添加@enablecaching注解:

@springbootapplication
@enablecaching
public class application {
    public static void main(string[] args) {
        springapplication.run(application.class, args);
    }
}

配置redis缓存管理器

@configuration
public class rediscacheconfig {
    @bean
    public rediscachemanager cachemanager(redisconnectionfactory connectionfactory) {
        rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig()
                .serializekeyswith(redisserializationcontext.serializationpair.fromserializer(new stringredisserializer()))
                .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(new genericjackson2jsonredisserializer()))
                .entryttl(duration.ofminutes(30)); // 默认过期时间30分钟
        return rediscachemanager.builder(connectionfactory)
                .cachedefaults(config)
                .withcacheconfiguration("usercache", rediscacheconfiguration.defaultcacheconfig().entryttl(duration.ofminutes(10))) // 自定义缓存过期
                .transactionaware()
                .build();
    }
}

usercache"这是缓存名称。在 spring 应用程序中,你可以通过指定不同的缓存名称来管理不同的缓存区域。

管理器中进行了与redis的连接还有序列化(数据库中存储的形式)

例如,如果你缓存了一个 user 对象,它会被序列化为 json 字符串,然后存储在 redis 中。在 redis 中,数据看起来可能是这样的:

"key": "{\"id\":\"1\",\"name\":\"john doe\",\"email\":\"john.doe@example.com\"}"

四.接下来就是要进行缓存管理

缓存操作管理通常有两种方式分别为 声明式注解缓存(annotation-based caching)命令式编程(imperative caching with redistemplate),接下来就谈谈我对这两种方法的理解及其运用

提示:通过我的rediscacheconfig文件序列化后,我们在redis数据库中的对象就是字符串类型的方式来存储

1.声明式注解缓存(annotation-based caching)

核心思想
通过 aop(面向切面编程)实现,开发者通过注解声明缓存行为,由框架自动完成缓存的读写和失效管理。

应用示例

(1) 读取数据优先缓存

@cacheable(value = "usercache", key = "#id", unless = "#result == null")
public user getuserbyid(long id) {
    return userrepository.findbyid(id).orelse(null);
}

原理:

方法执行前检查 usercache::id 是否存在(

value = "usercache"
标识该缓存属于名为usercache的缓存区(cache region),对应redis中的键前缀(如usercache::1)

key = "#id"
使用spel表达式定义缓存键,此处表示用方法参数id的值作为键的后缀

存在则直接返回缓存值

不存在则执行方法体,将结果存入缓存

unless 确保空值不缓存(防止缓存穿透)

(2) 更新数据后刷新缓存

@cacheput(value = "usercache", key = "#user.id")
public user updateuser(user user) {
    return userrepository.save(user); // 强制更新缓存
}

原理

  • 无论缓存是否存在,始终执行方法体
  • 将返回结果覆盖旧缓存

(3) 删除数据后清理缓存

@cacheevict(value = "usercache", key = "#id", beforeinvocation = true)
public void deleteuser(long id) {
    userrepository.deletebyid(id);
}

原理

  • beforeinvocation = true 表示在方法执行前删除缓存(避免方法执行失败导致缓存残留)

2.命令式编程缓存(imperative caching with redistemplate)

核心思想

通过 redistemplate 直接操作 redis 的 api,开发者需手动控制缓存逻辑,灵活性更高。

首先要配置一个redistemplate

import org.springframework.context.annotation.bean;  
import org.springframework.context.annotation.configuration;  
import org.springframework.data.redis.connection.redisconnectionfactory;  
import org.springframework.data.redis.core.redistemplate;  
import org.springframework.data.redis.serializer.genericjackson2jsonredisserializer;  
import org.springframework.data.redis.serializer.stringredisserializer;  
@configuration  
public class redisconfig {  
    @bean  
    public redistemplate<string, object> redistemplate(redisconnectionfactory redisconnectionfactory) {  
        redistemplate<string, object> template = new redistemplate<>();  
        template.setconnectionfactory(redisconnectionfactory);  
        // 设置 key 序列化器  
        template.setkeyserializer(new stringredisserializer());  
        // 设置 value 序列化器  
        template.setvalueserializer(new genericjackson2jsonredisserializer());  
        template.afterpropertiesset();  
        return template;  
    }  
}

redistemplate 是 spring data redis 提供的一个用于操作 redis 的模板类。它包含了很多操作 redis 的方法,主要分为以下几类:
通用操作
haskey(k key): 检查 key 是否存在。
delete(k key): 删除 key。
delete(collection<k> keys): 批量删除 keys。
expire(k key, long timeout, timeunit unit): 设置 key 的过期时间。
expireat(k key, date date): 设置 key 在指定时间过期。
keys(k pattern): 查找所有符合给定模式 pattern 的 key。
move(k key, int dbindex): 将 key 移动到指定的数据库。
randomkey(): 随机返回一个 key。
rename(k oldkey, k newkey): 重命名 key。
type(k key): 返回 key 的类型。
字符串操作
opsforvalue(): 获取字符串操作对象,进而可以使用如 set, get, increment, decrement 等方法。
列表操作
opsforlist(): 获取列表操作对象,进而可以使用如 leftpush, rightpush, range, size 等方法。
集合操作
opsforset(): 获取集合操作对象,进而可以使用如 add, members, size, ismember 等方法。
有序集合操作
opsforzset(): 获取有序集合操作对象,进而可以使用如 add, range, rangebyscore, score 等方法。
哈希操作
opsforhash(): 获取哈希操作对象,进而可以使用如 put, get, entries, keys, values 等方法。
事务操作
execute(rediscallback<t> action): 执行一个 rediscallback。
executepipelined(rediscallback<t> action): 以管道的方式执行多个命令。
multi(): 标记事务开始。
exec(): 执行所有事务块内的命令。
这些方法提供了对 redis 数据结构的基本操作,可以满足大部分的使用场景。需要注意的是,这些操作都是同步的,如果需要异步操作,可以使用 redistemplate 的异步版本 stringredistemplate。

应用示例

(1) 手动缓存读取与写入

public user getuserbyid(long id) {
    // 生成缓存键,格式为 "user:{id}"(如 "user:123")
    string cachekey = "user:" + id;
    // 获取 redis 的 string 类型操作接口
    valueoperations<string, user> ops = redistemplate.opsforvalue();
    // 尝试从 redis 中获取缓存数据
    user user = ops.get(cachekey);
    // 缓存未命中(包含空值标记的情况)
    if (user == null) {
        // 穿透到数据库查询真实数据
        user = userrepository.findbyid(id).orelse(null);
        if (user != null) {
            // 数据库存在数据:写入缓存并设置 30 分钟过期时间
            ops.set(cachekey, user, duration.ofminutes(30)); 
        } else {
            // 数据库不存在数据:写入特殊空值标记,设置 5 分钟较短过期时间
            // 使用 new nullvalue() 而非 null 是为了区分:
            // 1. 真实缓存空值(防止穿透)
            // 2. redis 未存储该键(真正的缓存未命中)
            ops.set(cachekey, new nullvalue(), duration.ofminutes(5));
        }
    }
    // 返回前进行空值标记判断
    return user instanceof nullvalue ? null : user;
}

特点:

完全手动控制缓存逻辑

可精细处理空值缓存和 ttl

(2) 操作复杂数据结构(hash)

public void updateuserprofile(long userid, map<string, string> profile) {
    string hashkey = "userprofiles";
    redistemplate.opsforhash().putall(hashkey, profile);
    // 设置整个 hash 的过期时间
    redistemplate.expire(hashkey, duration.ofhours(24));
}

3.两种方式的深度对比

维度声明式注解缓存 (@cacheable 等)命令式编程缓存 (redistemplate)
抽象层级高层抽象,屏蔽缓存实现细节底层操作,直接面向 redis api
代码侵入性无侵入(通过注解实现)显式代码调用
灵活性有限(受限于注解参数)极高(可自由操作所有 redis 命令)
数据结构支持仅支持简单键值对(通过序列化)支持所有 redis 数据结构(hash/list 等)
事务支持与 spring 事务管理集成需手动使用 multi/exec 或 sessioncallback
异常处理统一通过 cacheerrorhandler需自行 try-catch
缓存策略配置集中式配置(通过 rediscachemanager分散在代码各处
性能优化自动批量化(部分实现支持)分散在代码各处

最后 关键场景选择建议

(1) 优先使用注解的场景
简单的 crud 缓存需求

需要快速实现缓存逻辑

希望代码保持简洁(如业务层方法只需关注核心逻辑)

需要兼容多缓存后端(如同时支持 redis 和本地缓存)

(2) 必须使用命令式的场景
操作 redis 特有数据结构(如 geo、hyperloglog)

实现分布式锁、限流等高级功能

需要精细控制每个操作的 ttl

使用事务、pipeline 等 redis 特性

到此这篇关于redis在springboot中做缓存操作的两种方法的文章就介绍到这了,更多相关redis springboot缓存内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com