下载相关redis包启用命令:
go get github.com/gomodule/redigo/redis
获取到:
引入:
通过go,向redis写入数据string[key-val]
package main import ( "fmt" "github.com/gomodule/redigo/redis" //引入redis ) func main() { //通过go向redis写入数据和读取数据 //1.连接到redis conn, err := redis.Dial("tcp", "localhost:6379") if err != nil { fmt.Println("redis.Dial err=", err) return } fmt.Println("conn succ...", conn) defer conn.Close() //关闭... //2.通过go,向redis写入数据string[key-val] _, err = conn.Do("Set", "name", "tomjerry") if err != nil { fmt.Println("set err=", err) return } r, err := redis.String(conn.Do("Get", "name")) if err != nil { fmt.Println("set err=", err) return }//因为返回的r是Interface{} //因为name对应的值是string,因此我们需要转换 fmt.Println("操作ok ",r) }
通过go,向redis写入数据hash[key-val]
package main import ( "fmt" "github.com/gomodule/redigo/redis" //引入redis ) func main() { //通过go向redis写入数据和读取数据 //1.连接到redis conn, err := redis.Dial("tcp", "localhost:6379") if err != nil { fmt.Println("redis.Dial err=", err) return } // fmt.Println("conn succ...", conn) defer conn.Close() //关闭... //2.通过go,向redis写入数据hash[key-val] _, err = conn.Do("HSet", "user01", "name", "john") if err != nil { fmt.Println("hset err=", err) return } _, err = conn.Do("HSet", "user01", "age", 18) if err != nil { fmt.Println("hset err=", err) return } //2.通过go,向redis读入数据hash[key-val] r1, err := redis.String(conn.Do("HGet", "user01", "name")) if err != nil { fmt.Println("hgetr1 err=", err) return } r2, err := redis.Int(conn.Do("HGet", "user01", "age")) if err != nil { fmt.Println("hgetr2 err=", err) return }//因为返回的r是Interface{} //因为name对应的值是string,因此我们需要转换 fmt.Printf("操作ok r1=%v ,r2=%v", r1, r2) }
package main import ( "fmt" "github.com/gomodule/redigo/redis" //引入redis ) type Monster struct { Name string Age int Skill string } func monsterProcess(name string, age int, skill string) { //连接本地redis conn, err := redis.Dial("tcp", "localhost:6379") if err != nil { fmt.Println("redis.Dial err=", err) return } defer conn.Close() //关闭... _, err = conn.Do("HmSet", "monster", "name", name, "age", age, "skill", skill) //写入redis if err != nil { fmt.Println("hset err=", err) return } r, err := redis.Strings(conn.Do("HMGet", "monster", "name", "age", "skill")) for i, v := range r { fmt.Printf("r[%d]=%v\n",i,v) } } func main() { var monster Monster fmt.Println("请输入姓名:") fmt.Scanln(&monster.Name) fmt.Println("请输入年龄:") fmt.Scanln(&monster.Age) fmt.Println("请输入技能:") fmt.Scanln(&monster.Skill) monsterProcess(monster.Name ,monster.Age, monster.Skill) }