C'est La Vie

    人生无彩排,每一天都是现场直播!

    Go-Redis基本使用 — 增、删、读

    Go-Redis是Go语言的Redis驱动包。 下载地址:https://github.com/alphaze […]

    Go-Redis是Go语言的Redis驱动包。

    下载地址:https://github.com/alphazero/Go-Redis

    安装:

    # unzip Go-Redis-go1.zip
    # mv Go-Redis-go1 $GOPATH/src/pkg/redis
    # cd $GOPATH/src/pkg/redis
    # go install

    使用:

    读取数据:

    package main
    import (
    	"fmt"
    	"log"
    	"redis"
    )
    
    func main() {
    	// 连接Redis服务器 127.0.0.1:6379
    	spec := redis.DefaultSpec().Host("127.0.0.1").Port(6379)
    	client, e := redis.NewSynchClientWithSpec(spec)
    	// 是否连接出错
    	if e != nil {
    		log.Println("error on connect redis server")
    	}
    
    	// 取值并输出
    	value, err := client.Get("redis_key")
    	fmt.Println(fmt.Sprintf("%s", value))
    }
    

    写入数据:

    package main
    import (
    	"fmt"
    	"log"
    	"redis"
    )
    
    func main() {
    	// 连接Redis服务器 127.0.0.1:6379
    	spec := redis.DefaultSpec().Host("127.0.0.1").Port(6379)
    	client, e := redis.NewSynchClientWithSpec(spec)
    	// 是否连接出错
    	if e != nil {
    		log.Println("error on connect redis server")
    	}
    
    	// 设置并写入值
    	var data string = "redis data string"
    	client.Set("redis_key", []byte(data))
    }
    

    删除数据:

    package main
    import (
    	"fmt"
    	"log"
    	"redis"
    )
    
    func main() {
    	// 连接Redis服务器 127.0.0.1:6379
    	spec := redis.DefaultSpec().Host("127.0.0.1").Port(6379)
    	client, e := redis.NewSynchClientWithSpec(spec)
    	// 是否连接出错
    	if e != nil {
    		log.Println("error on connect redis server")
    	}
    
    	// 删除数据
    	client.Del("redis_key")
    }
    

    发表回复

    您的电子邮箱地址不会被公开。 必填项已用*标注