1. String类型 
基础命令
应用场景
- 共享session:在多服务器环境中共享用户会话。
代码示例
// 缓存商品信息
func cacheProductInfo(productID string, productInfo map[string]interface{}) {
    cacheKey := generateProductCacheKey(productID)
    productJSON, _ := json.Marshal(productInfo)
    rdb.Set(ctx, cacheKey, string(productJSON), 0) // 0表示永不过期
}
// 生成商品缓存键
func generateProductCacheKey(productID string) string {
    return "product:" + productID
}
2. List类型 
基础命令
- LPUSH key value:在列表头部插入元素。
- RPUSH key value:在列表尾部插入元素。
- LRANGE key start stop:获取列表指定范围内的元素。
应用场景
代码示例
// 将新订单添加到订单处理队列
func addOrderToQueue(order Order) {
    redisClient.LPUSH(ctx, "order_queue", order.ToString())
}
// 从订单处理队列中获取待处理的订单
func getNextOrder() (Order, error) {
    orderJSON, err := redisClient.RPOP(ctx, "order_queue").Result()
    if err != nil {
        return Order{}, err
    }
    var order Order
    json.Unmarshal([]byte(orderJSON), &order)
    return order, nil
}
3. Set类型 
基础命令
- SISMEMBER key member:检查元素是否在集合中。
- **SINTER key [key ...]**:取多个集合的交集。
- **SUNION key [key ...]**:取多个集合的并集。
- **SDIFF key [key ...]**:取集合的差集。
应用场景
代码示例
// 给文章添加标签
func addTagToArticle(articleID string, tag string) {
    redisClient.SADD(ctx, "article:"+articleID+":tags", tag)
}
// 根据标签获取文章列表
func getArticlesByTag(tag string) []string {
    return redisClient.SMEMBERS(ctx, "global:tags:"+tag).Val()
}
4. Sorted Set类型 
基础命令
- ZADD key score member:添加元素及其分数。
- **ZRANGE key start stop [WITHSCORES]**:按分数获取元素。
- ZINCRBY key increment member:增加元素的分数。
应用场景
代码示例
// 更新玩家得分
func updatePlayerScore(playerID string, score float64) {
    sortedSetKey := "playerScores"
    rdb.ZAdd(ctx, sortedSetKey, &redis.Z{Score: score, Member: playerID})
}
// 获取排行榜
func getLeaderboard(start int, stop int) []string {
    sortedSetKey := "playerScores"
    leaderboard, _ := rdb.ZRangeWithScores(ctx, sortedSetKey, start, stop).Result()
    var result []string
    for _, entry := range leaderboard {
        result = append(result, fmt.Sprintf("%s: %.2f", entry.Member.(string), entry.Score))
    }
    return result
}
5. Hash类型 
基础命令
- HSET key field value:设置字段的值。
- HINCRBY key field increment:增加字段的整数值。
应用场景
代码示例
// 存储用户信息到Redis Hash
func storeUserInfo(userID string, userInfo map[string]interface{}) {
    hashKey := "user:" + userID
    for field, value := range userInfo {
        rdb.HSet(ctx, hashKey, field, value)
    }
}
// 从Redis Hash获取用户信息
func getUserInfo(userID string) map[string]string {
    hashKey := "user:" + userID
    fields, err := rdb.HGetAll(ctx, hashKey).Result()
    if err != nil {
        return nil
    }
    var userInfo = make(map[string]string)
    for k, v := range fields {
        userInfo[k] = v
    }
    return userInfo
}
6. Bitmap类型 
基础命令
- SETBIT key offset value:设置位的值。
- **BITCOUNT key [start end]**:计算位值为1的数量。
- **BITOP operation destkey key [key ...]**:执行位运算。
应用场景
代码示例
// 更新玩家在线状态
func updatePlayerStatus(playerID int, isOnline bool) {
    bitmapKey := "playerStatus"
    offset := playerID
    if isOnline {
        rdb.SetBit(ctx, bitmapKey, int64(offset), 1)
    } else {
        rdb.SetBit(ctx, bitmapKey, int64(offset), 0)
    }
}
// 查询玩家在线状态
func checkPlayerStatus(playerID int) bool {
    bitmapKey := "playerStatus"
    offset := playerID
    bitValue, err := rdb.GetBit(ctx, bitmapKey, int64(offset)).Result()
    if err != nil {
        return false
    }
    return bitValue == 1
}
7. HyperLogLog类型 
基础命令
- **PFADD key element [element ...]**:添加元素到HyperLogLog。
- **PFCOUNT key [key ...]**:获取HyperLogLog中唯一元素的数量。
- **PFMERGE destkey sourcekey [sourcekey ...]**:合并多个HyperLogLog。
应用场景
代码示例
// 记录用户访问
func recordUserVisit(userID string) {
    uniqueSetKey := "uniqueVisitors"
    rdb.PFAdd(ctx, uniqueSetKey, userID)
}
// 获取唯一用户访问量
func getUniqueVisitorCount() int64 {
    uniqueSetKey := "uniqueVisitors"
    count, _ := rdb.PFCount(ctx, uniqueSetKey).Result()
    return count
}
8. GEO类型 
基础命令
- GEOADD key longitude latitude member:添加地理位置信息。
- GEOPOS key member [member ...]:获取成员的地理坐标。
- GEODIST key member1 member2 [unit]:计算两个成员之间的距离。
- GEOHASH key member [member ...]:获取成员的Geohash。
- GEORADIUS key longitude latitude radius unit [options]:搜索指定半径内的位置。
应用场景
代码示例
// 搜索附近地点
func searchNearbyPlaces(
longitude float64, latitude float64, radius float64) []string {
    geoSetKey := "touristSpots"
    places, _ := rdb.GeoRadius(
        ctx, geoSetKey, longitude, latitude, radius, "km",
        &redis.GeoRadiusQuery{WithCoord: true, WithDist: true, WithHash: true}).Result()
    var nearbyPlaces []string
    for _, place := range places {
        nearbyPlaces = append(nearbyPlaces, fmt.Sprintf("Name: %s, Distance: %.2f km", place.Member.(string), place.Dist))
    }
    return nearbyPlaces
}
注意事项 
- Bitmap和HyperLogLog类型适合处理大量数据的场景,但需要注意内存和性能的限制。
- GEO类型依赖于准确的经纬度信息,适用于需要地理位置服务的应用。
该文章在 2024/9/13 10:28:08 编辑过