1. 程式人生 > 實用技巧 >go語言操作redis

go語言操作redis

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("姓名\t年齡\t性別\n");
    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+"\t");
        }
        fmt.Println("\n");
    }
}