Go操作redis
2021-08-10 本文已影响0人
TZX_0710
//下载redis
go get github.com/gomodule/redigo/redis
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"reflect"
)
var pool *redis.Pool
func init() {
pool = &redis.Pool{
MaxIdle: 16, //最初的连接数量
MaxActive: 0,
IdleTimeout: 300, //连接关闭时间
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", "127.0.0.1:6379")
},
}
}
//set存储参数
func set(key, value interface{}) {
//获取连接
c := pool.Get()
_, err := c.Do("set", key, value)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("set success")
defer c.Close() //关闭连接
}
//Get获取参数
func get(key string) (value interface{}) {
c := pool.Get()
value, err := redis.String(c.Do("Get", key))
fmt.Println(reflect.TypeOf(value))
if err != nil {
fmt.Println(err)
return 0
}
fmt.Println()
defer c.Close()
return
}
func setEx(key string, value interface{}, ex int64) {
conn := pool.Get()
_, err := conn.Do("SET", key, value, "EX", ex)
if err != nil {
fmt.Println(err)
return
}
}
func main() {
set("name", "张三")
get("name")
//单位为秒
setEx("userId", 1, 10)
}