Spring Boot整合Redis注解,实战Redis注解使用

以下是一个基于Spring Boot整合Redis注解实现增删改查功能的实战教程,内容分为配置、实体类、Repository、Service及测试示例:


配置Redis连接

application.propertiesapplication.yml中添加Redis配置:

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

添加Spring Boot Redis依赖(Maven):

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

定义实体类

使用@RedisHash注解标记实体类,并定义主键:

java 复制代码
@RedisHash("User")
public class User {
    @Id
    private String id;
    private String name;
    private int age;
    // 省略getter/setter
}

创建Repository接口

继承CrudRepository并指定泛型类型:

java 复制代码
public interface UserRepository extends CrudRepository<User, String> {
}

增删改查操作示例

插入数据

通过save方法插入或更新数据:

java 复制代码
@Autowired
private UserRepository userRepository;

public void addUser(User user) {
    userRepository.save(user);
}
查询数据

使用findById或自定义查询方法:

java 复制代码
public User getUserById(String id) {
    return userRepository.findById(id).orElse(null);
}

// 自定义查询(需在Repository中声明方法)
@Indexed
public List<User> findByAge(int age);
删除数据

通过deleteById或对象删除:

java 复制代码
public void deleteUser(String id) {
    userRepository.deleteById(id);
}
更新数据

更新操作与插入相同(自动覆盖):

java 复制代码
public void updateUser(User user) {
    userRepository.save(user);
}

缓存注解应用

在Service层使用@Cacheable等注解实现缓存:

查询缓存
java 复制代码
@Service
public class UserService {
    @Cacheable(value = "users", key = "#id")
    public User getUser(String id) {
        // 模拟数据库查询
        return userRepository.findById(id).orElse(null);
    }
}
更新缓存
java 复制代码
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}
删除缓存
java 复制代码
@CacheEvict(value = "users", key = "#id")
public void deleteUser(String id) {
    userRepository.deleteById(id);
}

测试验证

编写测试类验证功能:

java 复制代码
@SpringBootTest
public class RedisTest {
    @Autowired
    private UserService userService;

    @Test
    public void testCrud() {
        User user = new User();
        user.setId("1");
        user.setName("Alice");
        userService.addUser(user);

        User cachedUser = userService.getUser("1");
        Assertions.assertNotNull(cachedUser);
    }
}

关键注解说明

  • @RedisHash:定义Redis中的存储哈希名称
  • @Id:标记主键字段
  • @Indexed:为字段创建二级索引
  • @Cacheable:查询时优先读取缓存
  • @CachePut:更新数据时同步更新缓存
  • @CacheEvict:删除数据时清除缓存

通过以上步骤即可实现Spring Boot与Redis注解的整合操作。注意缓存注解需在启动类添加@EnableCaching启用缓存功能。

相关推荐
mldong5 小时前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
陈随易5 小时前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron6 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境6 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境6 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
独行侠影a7 小时前
APScheduler+Redis 分布式定时任务:解决多实例任务重复执行
数据库·redis·分布式
IT_陈寒8 小时前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
SomeB1oody9 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程