Redis 核心使用場景
-
緩存加速
-
高頻訪問數據緩存(如商品信息、用戶信息)
-
緩解數據庫壓力,提升響應速度
-
-
會話存儲
-
分布式系統共享 Session(替代 Tomcat Session)
-
支持 TTL 自動過期
-
-
排行榜/計數器
-
實時排序(Sorted Set 實現)
-
文章閱讀量/點贊數統計(INCR 命令)
-
-
消息隊列
-
List 實現簡單隊列(LPUSH/BRPOP)
-
Streams 實現可靠消息隊列(Redis 5.0+)
-
-
分布式鎖
-
SETNX 命令實現互斥鎖
-
Redisson 客戶端封裝分布式鎖
-
-
實時系統
-
用戶行為記錄(最近搜索、瀏覽歷史)
-
實時數據統計(在線人數、地理位置)
-
Redis 數據類型與典型應用
數據類型 | 結構特征 | 典型場景 | 操作命令示例 |
---|---|---|---|
String | 二進制安全文本/數值 | 緩存、計數器、分布式鎖 | SET/GET/INCR/DECR |
Hash | 字段值映射表 | 存儲對象(用戶信息、商品詳情) | HSET/HGET/HGETALL |
List | 雙向鏈表 | 消息隊列、最新消息列表 | LPUSH/RPOP/LRANGE |
Set | 無序唯一集合 | 標簽系統、共同好友 | SADD/SMEMBERS/SINTER |
ZSet | 有序分值集合 | 排行榜、延遲隊列 | ZADD/ZRANGE/ZREVRANGE |
Stream | 消息流(持久化隊列) | 消息隊列(支持消費者組) | XADD/XREAD/XGROUP |
BitMap | 位操作 | 簽到統計、用戶畫像 | SETBIT/BITCOUNT/BITOP |
HyperLogLog | 基數估算算法 | UV 統計(去重計數) | PFADD/PFCOUNT |
鍵(Key)命名規范
-
層級結構:
業務模塊:子模塊:唯一標識
-
示例:
user:profile:1001
-
-
命名原則
-
長度 ≤ 100 字符
-
避免特殊字符(推薦字母數字 + 冒號)
-
可讀性優先(如?
order:status:2024
)
-
Spring Boot 集成實踐
1. 添加依賴
<!-- Spring Data Redis -->
<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>
2. 配置參數 (application.yml)
spring:redis:host: 127.0.0.1port: 6379password: yourpasswordlettuce:pool:max-active: 20max-idle: 10min-idle: 5
3. 核心組件配置
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);template.setKeySerializer(RedisSerializer.string());template.setValueSerializer(RedisSerializer.json());return template;}@Beanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {return new StringRedisTemplate(factory);}
}
4. 使用示例
@Component
public class UserService {private final RedisTemplate<String, User> redisTemplate;// 存儲用戶信息public void cacheUser(User user) {redisTemplate.opsForValue().set("user:" + user.getId(), user, 30, TimeUnit.MINUTES);}// 獲取用戶信息public User getCachedUser(Long userId) {return redisTemplate.opsForValue().get("user:" + userId);}// 使用 Hash 存儲對象public void cacheUserProfile(Long userId, Map<String, String> profile) {redisTemplate.opsForHash().putAll("user:profile:" + userId, profile);}
}
5. 注解緩存支持
@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory) {return RedisCacheManager.builder(factory).cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1))).build();}
}// 業務使用
@Service
public class ProductService {@Cacheable(value = "products", key = "#productId")public Product getProductById(String productId) {// 數據庫查詢邏輯}
}
最佳實踐建議
-
連接池配置:合理設置 max-active 防止連接耗盡
-
序列化選擇:優先使用 JSON 序列化(Jackson2JsonRedisSerializer)
-
大Key規避:String 類型 value ≤ 10KB,集合元素 ≤ 1萬
-
事務限制:Redis 事務非原子性,推薦使用 Lua 腳本
-
監控告警:集成 Prometheus + Grafana 監控 QPS、內存等指標
緩存穿透、緩存雪崩、緩存擊穿
問題 | 定義 | 后果 | 解決方案 |
---|---|---|---|
緩存穿透 | 請求的數據在緩存和數據庫中都不存在 | 大量無效請求打到數據庫 | 緩存空值、布隆過濾器、請求數據基礎格式校驗 |
緩存雪崩 | 大量緩存同時過期,導致請求打到數據庫 | 數據庫壓力驟增,可能崩潰 | 隨機過期時間、多級緩存、限流與降級、熱點數據永不過期 |
緩存擊穿 | 熱點 key 過期時,大量請求同時訪問 | 數據庫壓力瞬間增大 | 互斥鎖、邏輯過期、提前刷新 |