一、Redis介绍
1、Redis简介
Redis是一个开源的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。
2、Redis优点
(1)存取速度快
Redis速度非常快,每秒可执行大约110000次的设备操作,或者执行81000次的读取操作。
(2)支持丰富的数据类型
Redis支持开发人员常用的大多数数据类型,例如列表、集合、排序集和散列等。
(3)操作具有原子性
所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新后的值。
(4)提供多种功能
Redis提供了多种功能特性,可用作非关系型数据库、缓存中间件、消息中间件等。
二、使用SpringBoot整合Redis
1、在pom文件中添加Spring Data Redis依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、编写实体类
2.1 编写实体类Person
@RedisHash("persons") //存储实体到redis
public class Person{
@Id //用于标识实体类主键
private String id;
@Indexed //用于标识该属性会在redis数据库中生成二级索引
private String firstname;
@Indexed
private String lastname;
private Address address;
private List<Family>familyList;
......// get/set方法,以及tostring方法
}
2.2 编写实体类Family
public class Family{
@Indexed
private String type;
@Indexed
private String username;
......// get/set方法
}
2.3 编写实体类Address
public class Address{
@Indexed
private String city;
@Indexed
private String country;
......// get/set方法
}
3、编写Repository接口PersonRepository
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连接
#redis服务器地址
spring.redis.host=127.0.0.1
#redis连接端口
spring.redis.port=6379
#redis服务连接密码
spring.redis.password=xxxxxx
5、编写单元测试进行接口方法测试以及整合测试
@Autowired
private PersonRepository personRepository;
@Test
public void savePerson(){
Person person = new Person();
person.setFirstname("xx");
person.setlastname=("x);
Address address = new Address();
address.setCity("xx");
person.setAddress(address);
Family family=new Family();
family.setType("xxx");
family.setUsername("xx");
ArrayList<Family> families= new ArrayList<>();
families.add(family);
person.setFamilyList(families);
personRepository.save(person);
}