当前位置: 首页 > news >正文

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.propertiesapplication.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);}
}

六、高级配置与优化

  1. 自定义 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;}
    }
    
  2. 缓存注解集成
    结合 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);}
    }
    

七、注意事项

  1. 索引与查询性能
    @Indexed注解会为字段创建索引,提升查询效率,但会增加写入开销,按需使用。

  2. 事务支持
    Redis 本身不支持事务,但 Spring Data Redis 提供了RedisTransaction接口,可实现批量操作的原子性。

  3. 集群配置
    若使用 Redis 集群,需在配置中添加:

    spring.redis.cluster.nodes=192.168.1.1:7000,192.168.1.2:7001
    spring.redis.cluster.max-redirects=3
    

通过以上步骤,可在 Spring Boot 中高效整合 Redis,实现数据的缓存、高速查询及持久化存储。

相关文章:

  • 网站配色主题事件营销案例
  • wordpress博客导航windows11优化大师
  • 定制网站开发方案室内设计网站
  • 新版wordpress石家庄seo顾问
  • 线上新媒体电商怎么开店最新seo操作
  • 乐清建设路小学校园网站seo标题优化裤子关键词
  • 防御OSS Bucket泄露:RAM权限策略+日志审计+敏感数据扫描三重防护
  • 10.多进程服务器端
  • 复制 生成二维码
  • 麒麟V10操作系统离线安装Docker、Docker compose和1Panel
  • 鸿蒙 Stack 组件深度解析:层叠布局的核心应用与实战技巧
  • 6.24_JAVA_微服务_Elasticsearch搜索
  • 用Rust写平衡三进制加法器
  • 华为云Flexus+DeepSeek征文|基于华为云Flexus Dify复用优秀 AI Agent 应用教程
  • TMS汽车热管理系统HILRCP解决方案
  • FastMCP+python简单测试
  • Jenkins+Jmeter+Ant接口持续集成
  • 信创建设,如何统一管理异构服务器的认证、密码、权限管理等?
  • 配置自己的NTP 服务器做时间同步
  • 从零学习linux(2)——管理
  • 缺少 XML 验证与资源注入修复
  • Revisiting Image Deblurring with an Efficient ConvNet论文阅读
  • Joblib库多进程/线程使用(一):使用generator参数实现边响应边使用
  • leetcode61.旋转链表
  • 物流业最后的“人工堡垒”即将失守?机器人正式接管卡车装卸工作
  • java数据类型详解篇