Spring Data Redis 教程
本文我们介绍Spring Data Redis,它是对流行的内存数据库Redis在Spring data 框架下的抽象。
Redis使用键值对数据结构持久化数据,可以作为数据库、缓存、消息代理等。
我们能够使用Spring data通用模式(template等),同样也具有Spring data传统的简单性。
1. 环境配置
1.1. maven 依赖
首先声明Spring Data Redis依赖:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
</dependency>
读者可以选择合适版本。
1.2. Redis 配置
我们需要使用Redis client连接Redis,Redis提供了很多中实现,这里使用Jedis————简单强大的Redis客户端实现。Spring支持使用java或xml方式配置,这里使用Java方式进行配置。首先定义bean配置:
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
配置很简单,首先使用Jedis客户端,需要定义JedisConnectionFactory。然后,使用JedisConnectionFactory定义RedisTemplate,它可用于查询数据。
1.3. 自定义连接属性
你可能注意到没有用到常见的连接相关属性,举例服务器地址和端口号。原因很简单,我们使用了缺省配置。然而,如果需要配置连接信息,我们可以修改jedisConnectionFactory bean配置;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConFactory
= new JedisConnectionFactory();
jedisConFactory.setHostName("localhost");
jedisConFactory.setPort(6379);
return jedisConFactory;
}
2. 定义Redis Repository
首先定义Student实体类:
@RedisHash("Student")
public class Student implements Serializable {
public enum Gender {
MALE, FEMALE
}
private String id;
private String name;
private Gender gender;
private int grade;
// ...
}
因为有id字段,无需@Id注解。接着定义Repository:
@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}
使用Repository实现数据访问
通过扩展CrudRepository,我们自动获得完整持久化方法:
3.1. 保存数据
保存student对象至redis:
Student student = new Student(
"Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
3.2. 查询已存在对象
我们可以验证前面插入步骤是否正确:
Student retrievedStudent =
studentRepository.findById("Eng2015001").get();
3.3. 更新已存在对象
修改查询结果对象名称:
retrievedStudent.setName("Richard Watson");
studentRepository.save(student);
最后我们可以再次查询数据,验证名称是否被正确修改。
3.4. 删除已存在对象
下面删除上节插入的对象:
studentRepository.deleteById(student.getId());
现在查询验证,结果应该为null。
3.5. 查询所有对象数据
首先我们插入两个对象:
Student engStudent = new Student(
"Eng2015001", "John Doe", Student.Gender.MALE, 1);
Student medStudent = new Student(
"Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.save(engStudent);
studentRepository.save(medStudent);
当然也可以通过saveAll方法插入集合实现,其接收参数为Iterable类型。下面使用findAll方法查询所有对象:
List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);
读者可以简单通过list的size验证结果,也可以遍历集合细粒度验证每个对象属性。
4. 总结
本文我们介绍了Spring Data Redis,通过示例展示CRUD操作。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/103688416