golang基础-redis使用

前端之家收集整理的这篇文章主要介绍了golang基础-redis使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

redis安装

安装完毕后解压目录如下

点击redis-server.exe启动redis


然后在启动cmd客户端

set类型

package main

import (
    "fmt"

    "github.com/garyburd/redigo/redis"
)

func main() {
    var p *int
    var a int
    p = &a
    *p = 0

    c,err := redis.Dial("tcp","localhost:6379")
    if err != nil {
        fmt.Println("conn redis Failed,",err)
        return
    }

    defer c.Close()
    _,err = c.Do("Set","abc", 100)
    if err != nil {
        fmt.Println(err)
        return
    }
//redis-cli.exe -h 127.0.0.1 -p 6379
    r,err := redis.Int(c.Do("Get","abc"))
    if err != nil {
        fmt.Println("get abc Failed,err)
        return
    }

    fmt.Println(r)
}

输出如下:

PS E:\golang\go_pro\src\rediss> go run main.go
100

hash类型

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
)

func main() {
    c,err := redis.Dial("tcp","localhost:6379")
    if err != nil {
        fmt.Println("conn redis Failed,err)
        return
    }

    defer c.Close()
    _,err = c.Do("HSet","books",1000)
    if err != nil {
        fmt.Println(err)
        return
    }

    r,err := redis.Int(c.Do("HGet","abc"))
    if err != nil {
        fmt.Println("get abc Failed,err)
        return
    }

    fmt.Println(r)
}

输出如下:

PS E:\golang\go_pro\src\rediss> go run main.go
1000

批量set类型

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
)

func main() {
    c,err = c.Do("MSet",100,"efg",300)
    if err != nil {
        fmt.Println(err)
        return
    }

    r,err := redis.Ints(c.Do("MGet","efg"))
    if err != nil {
        fmt.Println("get abc Failed,err)
        return
    }

    for _,v := range r {
        fmt.Println(v)
    }
}

输出如下:

PS E:\golang\go_pro\src\rediss> go run main.go
100
300

队列操作

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
)

func main() {
    c,err = c.Do("lpush","book_list","ceg",30)
    if err != nil {
        fmt.Println(err)
        return
    }

    r,err := redis.String(c.Do("lpop","book_list"))
    if err != nil {
        fmt.Println("get abc Failed,err)
        return
    }

    fmt.Println(r)
}

输出如下:

PS E:\golang\go_pro\src\rediss> go run main.go
30

redis.Pool

package main

import (
    "fmt"

    "github.com/garyburd/redigo/redis"
)

var pool *redis.Pool

func init() {
    pool = &redis.Pool{
        MaxIdle:     16,MaxActive:   0,IdleTimeout: 300,Dial: func() (redis.Conn,error) {
            return redis.Dial("tcp","localhost:6379")
        },}
}

func main() {

    c := pool.Get()
    defer c.Close()

    _,err := c.Do("Set", 100)
    if err != nil {
        fmt.Println(err)
        return
    }

    r,err)
        return
    }

    fmt.Println(r)
    pool.Close()
}

输出如下:

PS E:\golang\go_pro\src\rediss> go run main.go
100
原文链接:https://www.f2er.com/go/187606.html

猜你在找的Go相关文章