GoWeb开发:010.Gin连接redis

144 阅读1分钟

安装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: "", // no password set
  DB:       0,  // use default DB
})
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
	}

	//以用户ID为key,用户名为值,写入redis,20秒后过期
	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"}

# 20s后再访问
$ curl 'localhost:9000/userget?id=1'
{"msg":"redis: nil"}