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 接口
相关推荐
智购科技无人售货机厂家3 小时前
2026自动售货机制冷系统维护指南:从散热器清洁到压缩机换油的工程实践~YH
运维·redis·物联网·缓存·架构
2601_962055973 小时前
跟据spring boot版本,查看对应的tomcat,并查看可支持的tomcat的版本范围
spring boot·后端·tomcat
EXI-小洲3 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
2601_961901705 小时前
SpringBoot使用Nacos进行application.yml配置管理
java·spring boot·spring
何以解忧,唯有..5 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
QQ_21696290966 小时前
【源码编号:project79475】SpringBoot校内二手交易平台:商品发布、分类检索、留言交流、订单管理全流程实战
java·spring boot·后端
前端 贾公子7 小时前
第09章:上下文与记忆 (2)
java·服务器·前端
2601_962203517 小时前
Java进阶07集合(续)
java·开发语言
郑州光合科技余经理7 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php
2601_962174177 小时前
Redis 简介
数据库·redis·wpf