首先在pom文件中添加Redis相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Redis数据库连接配置。在项目的全局配置文件application.properties中添加Redis数据库的连接
配置,示例代码如下:
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
编写Repository接口。Spring Boot针对包括Redis在内的一些常用数据库提供了自动化配置,可以通过实现Repository接口简化对数据库中的数据进行增删改查操作
public interface PersonRepository extends CrudRepository<Person,String> {
List<Person> findByAddress_City(String 北京);
}
测试类实现:
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
@Autowired
private PersonRepository repository;
@Test
public void savePerson() {
Person person = new Person();
person.setFirstname("张");
person.setLastname("三");
Address address = new Address();
address.setCity("北京");
address.setCountry("中国");
person.setAddress(address);
// 向Redis数据库添加数据
Person save = repository.save(person);
}
@Test
public void selectPerson() {
List<Person> list = (List<Person>) repository.findByAddress_City("北京");
for (Person person : list) {
System.out.println(person);
}
}