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 接口
相关推荐
风向决定发型丶18 小时前
redis集群搭建
数据库·redis·缓存
2501_9475758019 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计
骑士雄师20 小时前
java面试题 4:鉴权
java·开发语言
梦想的颜色20 小时前
硬核实践:使用 Docker 部署生产级 Redis(持久化 + 安全配置 + 高可用)
redis·docker·redis持久化·docker compose·redis哨兵·rdb aof
帅次21 小时前
Android 高级工程师面试:Java 基础知识 近1年高频追问 22 题
android·java·面试
蓝胖的四次元口袋21 小时前
Java集合(4)
java·哈希算法
2501_9481069121 小时前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
TanYYF21 小时前
spring ai入门教程二
java·人工智能·spring
SeeYa-J21 小时前
Spring IOC(Inversion of Control)
java·spring·rpc
宠友信息1 天前
多端数据互通场景下Spring Boot仿小红书源码结构设计
数据库·spring boot·redis·缓存·架构