go-redis/redis
地址:https://github.com/go-redis/redis
Supports:
- Redis 3 commands except QUIT, MONITOR, SLOWLOG and SYNC.
- Automatic connection pooling with circuit breaker support.
- Pub/Sub.
- Transactions.
- Pipeline and TxPipeline.
- Scripting.
- Timeouts.
- Redis Sentinel.
- Redis Cluster.
- Cluster of Redis Servers without using cluster mode and Redis Sentinel.
- Ring.
- Instrumentation.
- Cache friendly.
- Rate limiting.
- Distributed Locks.
安装
go get -u github.com/go-redis/redis
创建客户端
import "github.com/go-redis/redis"
func RedisInit(addr string) (*redis.Client,error) {
redisdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: "",
DB: 0,
PoolSize: 10,
})
_,err := redisdb.Ping().Result()
if err!=nil {
return nil,err
}else{
return redisdb,nil
}
}
redisdb,err:=RedisInit("192.168.10.25:6379")
RedisInit函数正确返回*redis.Client(redisdb),后续所有操作都使用这个redisdb
Hash操作
hset(key, field, value):向名称为key的hash中添加元素field。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HSet("h1","id1",1).Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hget(key, field):返回名称为key的hash中field对应的value。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HGet("h1","id1").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hmget(key, (fields)):返回名称为key的hash中field i对应的value。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HMGet("h1","id1","id2","id3").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hmset(key, (fields)):向名称为key的hash中添加元素field 。
func HashTest(redisdb *redis.Client) {
items:=map[string]interface{}{}
items["id1"]=1
items["id2"]=2
ret,err:=redisdb.HMSet("h1",items).Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hexists(key, field):名称为key的hash中是否存在键为field的域。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HExists("h1","id9").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
-----------------------------------------------------
判断h1中id9是否存在
hdel(key, field):删除名称为key的hash中键为field的域。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HDel("h1","id2").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hlen(key):返回名称为key的hash中元素个数。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HLen("h1").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hkeys(key):返回名称为key的hash中所有键。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HKeys("h1").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hvals(key):返回名称为key的hash中所有键对应的value。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HVals("h1").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}
hgetall(key):返回名称为key的hash中所有的键(field)及其对应的value。
func HashTest(redisdb *redis.Client) {
ret,err:=redisdb.HGetAll("h1").Result()
if err!=nil {
fmt.Println(err)
return
}
fmt.Println(ret)
}