springboot如何通过提供的注解方式来操作Redis

1.启用Redis注解支持

首先需要在配置类上添加 @EnableCaching 注解:

复制代码
@Configuration
@EnableCaching
public class RedisConfig {
    // 其他配置...
}

2.常用Redis操作注解

@Cacheable - 缓存查询

复制代码
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
    // 如果缓存中没有,则执行方法并将结果存入缓存
    return userRepository.findById(id).orElse(null);
}

参数说明:

  • value/cacheNames:缓存名称
  • key:缓存键,支持 SpEL 表达式
  • condition:条件缓存,满足条件才缓存
  • unless:条件不缓存,满足条件不缓存

@CachePut - 更新缓存

复制代码
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    // 更新数据库后,同时更新缓存
    return userRepository.save(user);
}

@CacheEvict - 删除缓存

复制代码
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    // 删除数据库记录后,同时删除缓存
    userRepository.deleteById(id);
}

@Caching - 组合多个缓存操作

复制代码
@Caching(
    cacheable = @Cacheable(value = "users", key = "#username"),
    evict = @CacheEvict(value = "userList", allEntries = true)
)
public User getUserByUsername(String username) {
    // 复杂缓存操作
    return userRepository.findByUsername(username);
}

3.自定义Key生成器

可以自定义缓存键生成策略:

复制代码
@Configuration
public class RedisConfig {
    
    @Bean
    public KeyGenerator customKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }
}

使用自定义 Key 生成器:

复制代码
@Cacheable(value = "users", keyGenerator = "customKeyGenerator")
public User getUserByEmail(String email) {
    // ...
}

4.条件缓存示例

复制代码
@Cacheable(value = "users", key = "#id", 
           condition = "#id > 10", unless = "#result == null")
public User getUserWithCondition(Long id) {
    // 只有当id>10时才缓存,且结果不为null时才缓存
    return userRepository.findById(id).orElse(null);
}

5.配置Redis连接

application.propertiesapplication.yml 中配置 Redis:

复制代码
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

6.Redis依赖

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 被注解的方法需要是 public 方法
  2. 自调用(同一个类中方法调用)不会触发缓存注解
  3. 对于复杂对象,确保实现了 Serializable 接口
相关推荐
javachen__1 小时前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
桦说编程7 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen7 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
记忆不曾留8 小时前
Mybatis 源码解读-SqlSession 会话源码和Executor SQL操作执行器源码
mybatis·二级缓存·sqlsession会话·executor执行器·一级缓存localcache
没有bug.的程序员8 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
一只爱撸猫的程序猿8 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
甄超锋8 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
阿华的代码王国9 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Zyy~9 小时前
《设计模式》装饰模式
java·设计模式