Go 语言入门很简单:Go 操作 Redis

515 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 24 天,点击查看活动详情

在 Redis 官网上有很多 Go 语言的客户端包,提供对 Redis 的访问和操作。

Go-Redis 是能够支持 Redis 集群的 Redis 客户端,是基于 Redigo 的 Redis 客户端的 Go 语言执行。Redis 客户端旨在控制每个节点的连接池,从而提高效率并减少延迟。本教程将介绍如何将 Redis Go 客户端 Go-Redis 与 Golang 一起使用。

安装 go-redis/redis

go get get github.com/go-redis/redis

创建 redis 链接

func rClient() *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	return client
}

上面的代码创建了一个新的 Redis 客户端,该客户端将连接到 Redis 服务器。此外,可以使用 &redis.Options 定义客户端和一些详细信息,例如 PoolSizeMaxRetriesPasswordDB。在此示例中,Addr 选项用于指定 Redis 服务器的主机名和端口号。

用 Redis Server 检查连接

可以使用如下的代码检查连接到 Redis Server 的状态:

func ping(client *redis.Client) error {
	pong, err := client.Ping().Result()
	if err != nil {
		return err
	}
	fmt.Println(pong, err)
	// Output: PONG <nil>

	return nil
}

上面的代码可以向 Redis 发送 ping 连接测试。如果成功,此测试将返回 PONG <nil> 作为结果,确认已建立与 Redis 服务器的连接,而不会出现错误。

如何使用 Redis 的 SET 命令

在 Redis 中可以使用 SET 命令设置键值对,如下:

127.0.0.1:6379> SET number "10086"
OK
127.0.0.1:6379> GET number
"10086"
127.0.0.1:6379>

接下来执行一个基础的 Redis 的 SET 命令,代码如下:

func set(client *redis.Client) error {
	err := client.Set("name", "Kyrie", 0).Err()
	if err != nil {
		return err
	}

	err = client.Set("country", "USA", 0).Err()
	if err != nil {
		return err
	}
	return nil
}

上面的代码可以设置一个 name 字符串,值为 Kyrie,country 为 USA

如何使用 Redis 的 GET 命令

本节将说明如何创建 Go 代码来查询上一节中的字符串指定的值。执行以下脚本以使用 GET 命令:

func get(client *redis.Client) error {
	nameVal, err := client.Get("name").Result()
	if err != nil {
		return (err)
	}
	fmt.Println("name", nameVal)

	countryVal, err := client.Get("country").Result()
	if err == redis.Nil {
		fmt.Println("no value found")
	} else if err != nil {
		panic(err)
	} else {
		fmt.Println("country", countryVal)
	}

	return nil
}

测试

接着,我们在 main() 函数中测试我们的代码:

func main() {

	// creates a client
	client := rClient()

	// check connection status
	err := ping(client)
	if err != nil {
		fmt.Println(err)
	}

	// Using the SET command to set Key-value pair
	err = set(client)
	if err != nil {
		fmt.Println(err)
	}

	// Using the GET command to get values from keys
	err = get(client)
	if err != nil {
		fmt.Println(err)
	}

}

运行结果:

PONG <nil>
name Kyrie
country USA

总结

本文介绍了如何将 Redis Go 客户端 go-Redis 与 Golang 一起使用。并且重点介绍了如何使用 go-redis/redis 客户端将 Redis 与 Golang 连接起来,并提供了一些示例,演示如何使用 Golang 脚本与 Redis 进行交互的 SETGET,在实际开发中可以结合着更多的方法进行使用。