安装Redis
1、Mac安装Redis
$ brew install redis
$ brew services start redis
$ brew services info redis
$ brew services stop redis
2、测试连接
$ redis-cli
127.0.0.1:6379> ping
PONG
Go连接Redis
1、安装go-redis库
$ go get -u github.com/redis/go-redis/v9
2、创建redis实例
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
3、写入值
r := gin.Default()
r.GET("/userset", func(c *gin.Context) {
userId := c.Query("id")
userName := c.Query("name")
if userId == "" {
c.JSON(500, gin.H{
"msg": "用户ID为空",
})
return
}
data, err := rdb.Set(c, userId, userName, time.Second*20).Result()
if err != nil {
c.JSON(500, gin.H{
"msg": err.Error(),
})
return
}
c.JSON(200, gin.H{
"data": data,
})
})
r.Run(":9000")
4、获取值
r.GET("/userget", func(c *gin.Context) {
userId := c.Query("id")
if userId == "" {
c.JSON(500, gin.H{
"msg": "用户ID为空",
})
return
}
data, err := rdb.Get(c, userId).Result()
if err != nil {
c.JSON(500, gin.H{
"msg": err.Error(),
})
return
}
c.JSON(200, gin.H{
"data": data,
})
})
5、示例
$ curl 'localhost:9000/userget?id=1'
{"msg":"redis: nil"}
$ curl 'localhost:9000/userset?id=1&name=jim'
{"data":"OK"}
$ curl 'localhost:9000/userget?id=1'
{"data":"jim"}
$ curl 'localhost:9000/userget?id=1'
{"msg":"redis: nil"}