//"github.com/garyburd/redigo/redis"
var Pool redis.Pool
func init() {
Pool = redis.Pool{
MaxIdle:16,
MaxActive:32,
IdleTimeout:120,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp","127.0.0.1:6379")
},
}
}
// 秒杀策略
func main() {
//redis.Dial()
c := Pool.Get()
res,err := c.Do("SET","name","jack")
if err != nil {
//错误处理
fmt.Println("conn redis failed,", err)
return
}else {
fmt.Println("连接成功",res)
}
res,err = redis.String(c.Do("GET","name"))
if err != nil {
//错误处理
fmt.Println("conn redis failed,", err)
return
}else {
fmt.Println("连接成功",res)
}
_,err = c.Do("expire","name",10)
if err != nil {
//错误处理
fmt.Println("过期时间设置失败,", err)
return
}else {
fmt.Println("过期时间设置成功")
}
_,err = c.Do("MSET","name1","小明","name2","小红")
if err != nil {
//错误处理
fmt.Println("批量设置失败,", err)
return
}else {
fmt.Println("批量设置成功")
}
res,err = redis.Strings(c.Do("MGET","name1","name2"))
if err != nil {
//错误处理
fmt.Println("批量设置失败,", err)
return
}else {
res_type := reflect.TypeOf(res)
fmt.Println("批量设置成功",res_type)
fmt.Println("批量设置成功",res)
}
// 队列
res,err = c.Do("LPUSH","List1","L1","L2","L3","L4")
if err != nil {
//错误处理
fmt.Println("队列设置失败,", err)
return
}else {
fmt.Println("队列设置成功",res)
}
res,err = redis.String(c.Do("RPOP","List1"))
if err != nil {
//错误处理
fmt.Println("队列获取失败,", err)
return
}else {
fmt.Println("队列获取成功",res)
}
// hash
res,err = c.Do("HSET","student_2","name_2","小雨","age_2","22")
if err != nil {
//错误处理
fmt.Println("HSET设置失败,", err)
return
}else {
fmt.Println("HSET设置成功",res)
}
res,err = redis.String(c.Do("HGET","student_2","age_2"))
if err != nil {
//错误处理
fmt.Println("HSET获取失败,", err)
return
}else {
fmt.Println("HSET获取成功",res)
}
//Pipelining(管道)
//Send(commandName string, args ...interface{}) error
//Flush() error
//Receive() (reply interface{}, err error)
//Send:发送命令至缓冲区
//Flush:清空缓冲区,将命令一次性发送至服务器
//Recevie:依次读取服务器响应结果,当读取的命令未响应时,该操作会阻塞。
c.Send("HSET","student_3","name","李明","age","23")
c.Send("HSET","student_3","Score","100")
c.Send("HGET","student_3","name")
c.Flush()
res1,err :=c.Receive()
fmt.Println("res1,", res1)
res2,err :=c.Receive()
fmt.Println("res2,", res2)
res3,err :=redis.String(c.Receive())
fmt.Println("res3,", res3)
}
2020/09/18 18:03:26 SUCCESS ▶ 0431 './smsTool' is running...
连接成功 OK
连接成功 jack
过期时间设置成功
批量设置成功
批量设置成功 []string
批量设置成功 [小明 小红]
队列设置成功 53
队列获取成功 L4
HSET设置成功 0
HSET获取成功 22
res1, 0
res2, 0
res3, 李明