1.在pom文件中添加spring-boot-starter-data-redis依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.编写三个实体类
@RedisHash("persons") // 指定操作实体类对象在Redis数据库中的存储空间
public class Person {
@Id// 标识实体类主键
private String id;
// 标识对应属性在Redis数据库中生成二级索引,索引名就是属性名,可以方便地进行数据条件查询
@Indexed
private String firstname;
@Indexed
private String lastname;
private Address address;
private List<Family>familyList;
public Person() { }
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
//补充get set toString
}
public class Address {
@Indexed
private String city;
@Indexed
private String country;
public Address() {
}
public Address(String city, String country) {
this.city = city;
this.country = country;
}
//补充get set toString
}
public class Family {
@Indexed
private String type;
@Indexed
private String username;
public Family() { }
public Family(String type, String username) {
this.type = type;
this.username = username;
}
//补充get set toString
}
3.编写Repository接口
不需要添加spring-boot-starter-data-jpa这个依赖,即:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
只要继承CrudRepository即可,如下:
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByLastname(String lastname);
Page<Person> findPersonByLastname(String lastname, Pageable page);
List<Person> findByFirstnameAndLastname(String firstname, String lastname);
List<Person> findByAddress_City(String city);
List<Person> findByFamilyList_Username(String username);
}
4.在全局配置文件application.properties中添加Redis数据库连接配置
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
5.编写单元测试进行接口方法测试以及整合测试
@SpringBootTest
public class RedisTests {
@Autowired
private PersonRepository repository;
@Test
public void savePerson() {
Person person =new Person("张","有才");
Person person2 =new Person("James","Harden");
// 创建并添加住址信息
Address address=new Address("北京","China");
person.setAddress(address);
// 创建并添加家庭成员
List<Family>list =new ArrayList<>();
Family dad =new Family("父亲","张良");
Family mom =new Family("母亲","李香君");
list.add(dad);
list.add(mom);
person.setFamilyList(list);
// 向Redis数据库添加数据
Person save = repository.save(person);
Person save2 = repository.save(person2);
System.out.println(save);
System.out.println(save2);
}
@Test
public void selectPerson() {
List<Person>list = repository.findByAddress_City("北京");
System.out.println(list);
}
@Test
public void updatePerson() {
Person person = repository.findByFirstnameAndLastname("张","有才").get(0);
person.setLastname("小明");
Person update = repository.save(person);
System.out.println(update);
}
@Test
public void deletePerson() {
Person person = repository.findByFirstnameAndLastname("张","小明").get(0);
repository.delete(person);
}
}