Golang 入门系列(七)Redis的使用

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Golang 入门系列(七)Redis的使用 安装 1. Redis 的安装很简单,我这里测试直接用的是windows 的版本。如何安装就不细说了。想了解的可以看之前的文章:https://www.cnblogs.

Golang 入门系列(七)Redis的使用

安装

1. Redis 的安装很简单,我这里测试直接用的是windows 的版本。如何安装就不细说了。想了解的可以看之前的文章:https://www.cnblogs.com/zhangweizhong/category/771056.html
 
2. golang 客户端,用的是 go-redis,
  1.   go get github.com/go-redis
       2.  接着在代码中导入此包即可: 
  import "github.com/go-redis/redis"
 

基本操作

创建Redis连接客户端

通过 redis.NewClient 函数即可创建一个 redis 客户端, 这个方法接收一个 redis.Options 对象参数, 通过这个参数, 我们可以配置 redis 相关的属性, 例如 redis 服务器地址, 数据库名, 数据库密码等。
// 创建 redis 客户端
复制代码
func GetRedisClient() *Client {
    redisdb := NewClient(&Options{
        Addr:     "127.0.0.1:6379",
        Password: "", // no password set
        DB:       0,                 // use default DB
    })

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}
复制代码

通过 cient.Ping() 来检查是否成功连接到了 redis 服务器

 

String 操作

  S et(key, value):给数据库中名称为key的string赋予值valueget(key):返回数据库中名称为key的string的value
  GetSet(key, value):给名称为key的string赋予上一次的value
  MGet(key1, key2,…, key N):返回库中多个string的value
  SetNX(key, value):添加string,名称为key,值为value
  SetXX(key, time, value):向库中添加string,设定过期时间time
  MSet(key N, value N):批量设置多个string的值
  MSetNX(key N, value N):如果所有名称为key i的string都不存在
  Incr(key):名称为key的string增1操作
  Incrby(key, integer):名称为key的string增加integer
  Decr(key):名称为key的string减1操作
  Decrby(key, integer):名称为key的string减少integer
  Append(key, value):名称为key的string的值附加valuesubstr(key, start, end):返回名称为key的string的value的子串
复制代码
func StringDemo() {
    fmt.Println("-----------------------welcome to StringDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient ==nil{
        fmt.Errorf("StringDemo redisClient is nil")
        return
    }

    name := "张三"
    key :="name:zhangsan"
    redisClient.Set(key , name,1 * time.Second)
    val := redisClient.Get(key)
    if val == nil {
        fmt.Errorf("StringDemo get error")
    }
    fmt.Println("name", val)
}
复制代码

 

List 操作

  RPush(key, value):在名称为key的list尾添加一个值为value的元素
  LPush(key, value):在名称为key的list头添加一个值为value的 元素
  LLen(key):返回名称为key的list的长度
  LRange(key, start, end):返回名称为key的list中start至end之间的元素
  LTrim(key, start, end):截取名称为key的list
  LIndex(key, index):返回名称为key的list中index位置的元素
  LSet(key, index, value):给名称为key的list中index位置的元素赋值
  LRem(key, count, value):删除count个key的list中值为value的元素
  LPop(key):返回并删除名称为key的list中的首元素
  RPop(key):返回并删除名称为key的list中的尾元素
  BLPop(key1, key2,… key N, timeout):lpop命令的block版本。
  BRPop(key1, key2,… key N, timeout):rpop的block版本。
  RPopLPush(srckey, dstkey):返回并删除名称为srckey的list的尾元素,并将该元素添加到名称为dstkey的list的头部
复制代码
func ListDemo(){
    fmt.Println("-----------------------welcome to ListDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("ListDemo redisClient is nil")
        return
    }
    articleKey := "article"
    result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    result,err = redisClient.LPush(articleKey, "d").Result() //
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    length, err := redisClient.LLen(articleKey).Result()
    if err != nil {
        fmt.Println("ListDemo LLen is nil")
    }
    fmt.Println("length: ", length) // 长度

    mapOut,err1:=redisClient.LRange(articleKey,0,100).Result()
    if err1!=nil {
        fmt.Println(err1)
        return
    }
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
}
复制代码

Hash 操作

  HSet(key, field, value):向名称为key的hash中添加元素field
  HGet(key, field):返回名称为key的hash中field对应的value
  HMget(key, (fields)):返回名称为key的hash中field i对应的value
  HMset(key, (fields)):向名称为key的hash中添加元素field
  HIncrby(key, field, integer):将名称为key的hash中field的value增加integer
  HExists(key, field):名称为key的hash中是否存在键为field的域
  HDel(key, field):删除名称为key的hash中键为field的域
  HLen(key):返回名称为key的hash中元素个数
  HKeys(key):返回名称为key的hash中所有键
  HVals(key):返回名称为key的hash中所有键对应的value
  HGetall(key):返回名称为key的hash中所有的键(field)及其对应的value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
func HashDemo() {
     fmt.Println( "-----------------------welcome to HashDemo-----------------------" )
     redisClient := GetRedisClient()
     if  redisClient == nil {
         fmt.Errorf( "HashDemo redisClient is nil" )
         return
     }
     article := Article{18,  "测试文章内容22222" "测试文章内容22222测试文章内容22222测试文章内容22222" , 10, 0}
     articleKey :=  "article:18"
 
     redisClient.HMSet(articleKey, ToStringDictionary(&article))
     mapOut := redisClient.HGetAll(articleKey).Val()
     for  inx, item := range mapOut {
         fmt.Printf( "\n %s:%s" , inx, item)
     }
     fmt.Print( "\n" )
 
     redisClient.HSet(articleKey,  "Content" "测试文章内容" )
     mapOut = redisClient.HGetAll(articleKey).Val()
     for  inx, item := range mapOut {
         fmt.Printf( "\n %s:%s" , inx, item)
     }
     fmt.Print( "\n" )
 
     view, err := redisClient.HIncrBy(articleKey,  "Views" , 1).Result()
     if  err != nil {
         fmt.Printf( "\n HIncrBy error=%s " , err)
     else  {
         fmt.Printf( "\n HIncrBy Views=%d " , view)
     }
     fmt.Print( "\n" )
 
     mapOut = redisClient.HGetAll(articleKey).Val()
     for  inx, item := range mapOut {
         fmt.Printf( "\n %s:%s" , inx, item)
     }
     fmt.Print( "\n" )
 
}

连接池

go-redis 已经实现了 redis 的连接池管理, 因此我们不需要自己手动管理 redis 的连接。
默认情况下,连接池大小是10, 可以通过 redis.Options 的 PoolSize 属性, 我们设置了 redis 连接池的大小为5。
复制代码
func GetRedisClientPool() *Client{
    redisdb := NewClient(&Options{
        Addr: "127.0.0.1:6379",
        Password: "",
        DB: 0,
        PoolSize: 5,})

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}
复制代码
复制代码
// 连接池测试
func connectPoolTest() {
    fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
    client :=GetRedisClientPool()
    wg := sync.WaitGroup{}
    wg.Add(10)

    for i := 0; i < 10; i++ {
        go func() {
            defer wg.Done()

            for j := 0; j < 1000; j++ {
                client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), 0).Err()
                client.Get(fmt.Sprintf("name%d", j)).Result()
            }

            fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
        }()
    }

    wg.Wait()
}
复制代码

完整代码

复制代码
package main

import (
    "fmt"
    . "github.com/go-redis/redis"
    . "redisDemo/models"
    "time"
    "sync"
)

func main() {
    fmt.Println("-----------------------welcome to redisdemo-----------------------")
    //StringDemo()
    //ListDemo()
    //HashDemo()
    connectPoolTest()
}

func StringDemo() {
    fmt.Println("-----------------------welcome to StringDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient ==nil{
        fmt.Errorf("StringDemo redisClient is nil")
        return
    }

    name := "张三"
    key :="name:zhangsan"
    redisClient.Set(key , name,1 * time.Second)
    val := redisClient.Get(key)
    if val == nil {
        fmt.Errorf("StringDemo get error")
    }
    fmt.Println("name", val)
}

func ListDemo(){
    fmt.Println("-----------------------welcome to ListDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("ListDemo redisClient is nil")
        return
    }
    articleKey := "article"
    result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //在名称为 key 的list尾添加一个值为value的元素
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    result,err = redisClient.LPush(articleKey, "d").Result() //在名称为 key 的list头添加一个值为value的元素
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    length, err := redisClient.LLen(articleKey).Result()
    if err != nil {
        fmt.Println("ListDemo LLen is nil")
    }
    fmt.Println("length: ", length) // 长度

    mapOut,err1:=redisClient.LRange(articleKey,0,100).Result()
    if err1!=nil {
        fmt.Println(err1)
        return
    }
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
}

func HashDemo() {
    fmt.Println("-----------------------welcome to HashDemo-----------------------")
    redisClient := GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("HashDemo redisClient is nil")
        return
    }
    article := Article{18, "测试文章内容22222", "测试文章内容22222测试文章内容22222测试文章内容22222", 10, 0}
    articleKey := "article:18"

    redisClient.HMSet(articleKey, ToStringDictionary(&article))
    mapOut := redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    redisClient.HSet(articleKey, "Content", "测试文章内容")
    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    view, err := redisClient.HIncrBy(articleKey, "Views", 1).Result()
    if err != nil {
        fmt.Printf("\n HIncrBy error=%s ", err)
    } else {
        fmt.Printf("\n HIncrBy Views=%d ", view)
    }
    fmt.Print("\n")

    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

}

func GetRedisClient() *Client {
    redisdb := NewClient(&Options{
        Addr:     "127.0.0.1:6379",
        Password: "", // no password set
        DB:       0,                 // use default DB
    })

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}

func GetRedisClientPool() *Client{
    redisdb := NewClient(&Options{
        Addr: "127.0.0.1:6379",
        Password: "",
        DB: 0,
        PoolSize: 5,})

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}

// 连接池测试
func connectPoolTest() {
    fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
    client :=GetRedisClientPool()
    wg := sync.WaitGroup{}
    wg.Add(10)

    for i := 0; i < 10; i++ {
        go func() {
            defer wg.Done()

            for j := 0; j < 1000; j++ {
                client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), 0).Err()
                client.Get(fmt.Sprintf("name%d", j)).Result()
            }

            fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
        }()
    }

    wg.Wait()
}
复制代码

最后

1. go语言使用Redis 还是非常简单的,以上已经把Redis 的基本的用法讲完了。大家可以自己动手写代码试试。

2. 完整代码:点击下载

原文地址https://www.cnblogs.com/zhangweizhong/p/10341460.html

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
11天前
|
存储 缓存 NoSQL
【Go语言专栏】Go语言中的Redis操作与缓存应用
【4月更文挑战第30天】本文探讨了在Go语言中使用Redis进行操作和缓存应用的方法。文章介绍了Redis作为高性能键值存储系统,用于提升应用性能。推荐使用`go-redis/redis`库,示例代码展示了连接、设置、获取和删除键值对的基本操作。文章还详细阐述了缓存应用的步骤及常见缓存策略,包括缓存穿透、缓存击穿和缓存雪崩的解决方案。利用Redis和合适策略可有效优化应用性能。
|
3天前
|
NoSQL 关系型数据库 MySQL
redis 入门01
redis 入门01
8 0
|
9天前
|
缓存 NoSQL Java
【Redis系列笔记】Redis入门
本文介绍了Redis常用命令,以及SpringBoot集成Spring Data Redis和Spring Cache。Spring Data Redis 提供了对 Redis 的操作方法,而 Spring Cache 则提供了基于注解的缓存功能,可以方便地将方法的返回值缓存到 Redis 中,以提高性能和减少对数据源的访问次数。这样的集成可以帮助开发者更便捷地利用 Redis 来管理应用程序的数据和缓存。
84 4
|
11天前
|
NoSQL Shell Go
在go中简单使用go-redis库
在go中简单使用go-redis库
|
16天前
|
存储 缓存 NoSQL
Redis入门到通关之Redis内存淘汰(内存过期)策略
Redis入门到通关之Redis内存淘汰(内存过期)策略
31 3
|
16天前
|
存储 NoSQL Linux
Redis入门到通关之多路复用详解
Redis入门到通关之多路复用详解
20 1
|
16天前
|
存储 NoSQL Linux
Redis入门到通关之Redis5种网络模型详解
Redis入门到通关之Redis5种网络模型详解
32 1
|
16天前
|
NoSQL Ubuntu 关系型数据库
Redis入门到通关之Redis网络模型-用户空间和内核态空间
Redis入门到通关之Redis网络模型-用户空间和内核态空间
22 1
|
16天前
|
存储 NoSQL 算法
Redis入门到通关之Redis数据结构-Hash篇
Redis入门到通关之Redis数据结构-Hash篇
20 1
|
16天前
|
存储 NoSQL Redis
Redis入门到通关之Redis数据结构-Set篇
Redis入门到通关之Redis数据结构-Set篇
20 1