1.使用hash存储
package main import ( "bufio" "fmt" "github.com/gomodule/redigo/redis" "os" "strconv" ) func main(){ id:=1; conn,err:=redis.Dial("tcp","127.0.0.1:6379"); defer conn.Close(); if err !=nil { fmt.Println("connect redis is error"); return; } for{ if id >=3 { break; } userId := "user_"+strconv.Itoa(id); fmt.Println(userId); fmt.Println("请输入用户名:"); readName:=bufio.NewReader(os.Stdin); sliceName,_,_:=readName.ReadLine(); name:=string(sliceName); fmt.Println("请输入年龄:"); readAge:=bufio.NewReader(os.Stdin); sliceage,_,_:=readAge.ReadLine(); age:=string(sliceage); fmt.Println("请输入性别:"); readSex:= bufio.NewReader(os.Stdin); sliceSex,_,_:=readSex.ReadLine(); sex:=string(sliceSex); conn.Do("hset",userId,"id",id); conn.Do("hset",userId,"name",name); conn.Do("hset",userId,"age",age); conn.Do("hset",userId,"sex",sex); id++; } }
2.遍历redis操作
package main import ( "fmt" "github.com/gomodule/redigo/redis" ) func main(){ conn,err:=redis.Dial("tcp","127.0.0.1:6379"); if err != nil { fmt.Println("connect redis is error"); return; } list,err:=redis.Strings(conn.Do("keys","user_*")); fmt.Println("姓名 年龄 性别 "); for _,v:=range list { info,err:=redis.Strings(conn.Do("hmget",v,"name","age","sex")); if err != nil { fmt.Println("get data is err"); } for _,val:=range info { fmt.Print(val+" "); } fmt.Println(" "); } }