一、依賴引入與基礎配置
-
添加依賴
在pom.xml
中引入 Spring Data Redis 的 Starter 依賴,默認使用 Lettuce 客戶端:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 連接池支持 --> <dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId> </dependency>
-
連接配置
在application.yml
中配置 Redis 服務器信息及連接池參數:spring:redis:host: localhostport: 6379password: 123456 # 可選database: 0lettuce:pool:max-active: 16 # 最大活躍連接數max-idle: 8 # 最大空閑連接min-idle: 2 # 最小空閑連接max-wait: 5000ms # 等待超時時間
二、核心功能與基本操作
-
RedisTemplate 與序列化
? 默認序列化問題:默認使用 JDK 序列化,存儲二進制數據不可讀。? 自定義序列化:改用 JSON 或字符串序列化:
@Configuration public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setKeySerializer(RedisSerializer.string());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(factory);return template;} }
-
數據結構操作
通過RedisTemplate
支持多種 Redis 數據結構:
? 字符串(String):redisTemplate.opsForValue().set("key", "value", 60, TimeUnit.SECONDS); // 帶過期時間 String value = redisTemplate.opsForValue().get("key");
? 哈希(Hash):
redisTemplate.opsForHash().put("user:1001", "name", "Alice"); Object name = redisTemplate.opsForHash().get("user:1001", "name");
? 列表(List):
redisTemplate.opsForList().rightPush("listKey", "item1"); List<Object> items = redisTemplate.opsForList().range("listKey", 0, -1);
三、高級特性與優化
-
緩存管理
? 啟用緩存注解:通過@EnableCaching
和@Cacheable
實現聲明式緩存:@Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { ... }
? 自定義緩存配置:指定 TTL(過期時間)和緩存條件。
-
事務與管道(Pipeline)
? 事務操作:通過SessionCallback
實現原子性操作:redisTemplate.execute(new SessionCallback<>() {@Overridepublic List<Object> execute(RedisOperations operations) {operations.multi();operations.opsForValue().set("key1", "value1");operations.opsForValue().set("key2", "value2");return operations.exec();} });
? 管道批量操作:提升網絡性能:
redisTemplate.executePipelined((RedisCallback<Object>) connection -> {connection.stringCommands().set("key1".getBytes(), "value1".getBytes());connection.stringCommands().set("key2".getBytes(), "value2".getBytes());return null; });
-
異步與響應式編程
? Lettuce 異步 API:非阻塞操作提升并發性能:RedisAsyncCommands<String, String> asyncCommands = lettuceConnection.async(); RedisFuture<String> future = asyncCommands.get("key"); future.thenAccept(System.out::println);
四、常見問題與解決方案
-
序列化不一致
? 問題:默認 JDK 序列化導致存儲數據不可讀。? 解決:使用
StringRedisTemplate
或自定義 JSON 序列化。 -
連接池配置優化
? 參數調優:根據并發量調整max-active
和max-idle
,避免資源耗盡。 -
緩存穿透與雪崩
? 穿透:緩存空值或布隆過濾器攔截非法請求。? 雪崩:分散過期時間或使用分布式鎖。
五、生產環境建議
-
監控與診斷
? 使用 Redis Desktop Manager 或 Prometheus 監控連接池狀態與性能指標。 -
高可用部署
? 結合 Redis Sentinel 或 Cluster 實現高可用。
總結
spring-boot-starter-data-redis
通過簡化的配置和強大的 RedisTemplate
抽象,為開發者提供了高效的 Redis 集成方案。合理配置序列化與連接池參數,結合事務、管道等高級特性,可顯著提升應用性能。對于大規模生產環境,建議進一步整合 Redis 集群與監控工具以實現高可用與穩定性。