58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
|
package main
|
|||
|
|
|||
|
import (
|
|||
|
"fmt"
|
|||
|
"github.com/go-redis/redis"
|
|||
|
)
|
|||
|
|
|||
|
// redis
|
|||
|
// 与mysql类似,也是一个连接池对象
|
|||
|
var redisdb *redis.Client
|
|||
|
|
|||
|
func initRedis() (err error) {
|
|||
|
//这里不要声明为局部变量
|
|||
|
redisdb = redis.NewClient(&redis.Options{
|
|||
|
Addr: "43.143.245.135:6379",
|
|||
|
Password: "ningzaichun",
|
|||
|
DB: 0,
|
|||
|
})
|
|||
|
pong, err := redisdb.Ping().Result()
|
|||
|
if err != nil {
|
|||
|
return err
|
|||
|
}
|
|||
|
fmt.Println("pong", pong)
|
|||
|
return nil
|
|||
|
|
|||
|
}
|
|||
|
func main() {
|
|||
|
err := initRedis()
|
|||
|
if err != nil {
|
|||
|
fmt.Println("connect redis failed", err)
|
|||
|
return
|
|||
|
}
|
|||
|
fmt.Println("redis connect success")
|
|||
|
|
|||
|
//zset
|
|||
|
key := "rank"
|
|||
|
languages := []redis.Z{
|
|||
|
{Score: 90.0, Member: "Golang"},
|
|||
|
{Score: 98.0, Member: "Java"},
|
|||
|
{Score: 95.0, Member: "Python"},
|
|||
|
{Score: 97.0, Member: "JavaScript"},
|
|||
|
{Score: 99.0, Member: "C/C++"},
|
|||
|
}
|
|||
|
//把元素追加到key
|
|||
|
num, err := redisdb.ZAdd(key, languages...).Result()
|
|||
|
if err != nil {
|
|||
|
fmt.Println("add languages failed", err)
|
|||
|
}
|
|||
|
fmt.Println("add languages success", num)
|
|||
|
//给Golang加10分
|
|||
|
newScore, err := redisdb.ZIncrBy(key, 10, "Golang").Result()
|
|||
|
if err != nil {
|
|||
|
fmt.Printf("zincrby failed, err:%v\n", err)
|
|||
|
return
|
|||
|
}
|
|||
|
fmt.Printf("Golang's score is %f now.\n", newScore)
|
|||
|
}
|