Spring Boot 中整合 Redis
Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理。
自行从官网下载 redis
前端查询工具:RedisDesktopManager
在 Spring Boot 中整合 Redis 主要包含依赖添加、实体类定义、Repository 接口编写、配置文件设置及测试等步骤,以下是详细实现流程:
一、添加 Redis 依赖
在pom.xml
中引入 Spring Data Redis 启动器:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、定义实体类
使用@RedisHash
注解标记实体类,并通过@Id
、@Indexed
等注解配置字段映射:
// Person.java
@RedisHash("persons") // 定义Redis中存储的哈希表名
public class Person {@Id // 主键标识private String id;@Indexed // 标记可索引字段,用于查询private String firstname;@Indexedprivate String lastname;private Address address;private List<Family> familyList;// 构造方法、getter和setter省略
}// Address.java
public class Address {@Indexedprivate String city;@Indexedprivate String country;// getter和setter省略
}// Family.java
public class Family {@Indexedprivate String type;@Indexedprivate String username;// getter和setter省略
}
三、编写 Repository 接口
继承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);
}
四、配置 Redis 连接
在application.properties
或application.yml
中添加 Redis 服务器连接信息:
# application.properties配置
spring.redis.host=127.0.0.1 # Redis服务器地址
spring.redis.port=6379 # Redis端口
spring.redis.password= # Redis密码(若无则留空)
spring.redis.database=0 # 使用的数据库索引(默认0)
spring.redis.timeout=3000ms # 连接超时时间
五、编写测试类
通过单元测试验证 Redis 操作功能:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {@Autowiredprivate PersonRepository repository;@Testpublic void testFindByCity() {// 查询地址为"北京"的所有PersonList<Person> list = repository.findByAddress_City("北京");list.forEach(System.out::println);}@Testpublic void testPagedQuery() {// 按姓氏分页查询(第1页,每页10条)Page<Person> page = repository.findPersonByLastname("张", PageRequest.of(0, 10));System.out.println("总记录数:" + page.getTotalElements());page.getContent().forEach(System.out::println);}@Testpublic void testSavePerson() {// 保存数据到RedisPerson person = new Person();person.setId("1");person.setFirstname("张三");person.setLastname("张");// 配置address和familyList...repository.save(person);}
}
六、高级配置与优化
-
自定义 RedisTemplate:
若需自定义序列化方式(如使用 JSON 序列化替代默认的 JDK 序列化),可添加配置类:java
@Configuration public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// 使用JSON序列化Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);template.setValueSerializer(serializer);template.setHashValueSerializer(serializer);// 字符串键序列化template.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.afterPropertiesSet();return template;} }
-
缓存注解集成:
结合 Spring Cache 注解简化缓存操作(需在启动类添加@EnableCaching
):@Service public class PersonService {@Autowiredprivate PersonRepository repository;@Cacheable(value = "persons", key = "#id")public Person getPersonById(String id) {return repository.findById(id).orElse(null);}@CacheEvict(value = "persons", key = "#id")public void deletePerson(String id) {repository.deleteById(id);} }
七、注意事项
-
索引与查询性能:
@Indexed
注解会为字段创建索引,提升查询效率,但会增加写入开销,按需使用。 -
事务支持:
Redis 本身不支持事务,但 Spring Data Redis 提供了RedisTransaction
接口,可实现批量操作的原子性。 -
集群配置:
若使用 Redis 集群,需在配置中添加:spring.redis.cluster.nodes=192.168.1.1:7000,192.168.1.2:7001 spring.redis.cluster.max-redirects=3
通过以上步骤,可在 Spring Boot 中高效整合 Redis,实现数据的缓存、高速查询及持久化存储。