go操作redis和mysql示例

一:redis示例


 使用redis的包是: github.com/garyburd/redigo/redis

1:编写第一个示例: 链接,设置,获取

redis_basic.go

package main

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

func main() {
    c, err := redis.Dial("tcp", "192.168.0.109:6379")  //连接到redis
    if err != nil {
        fmt.Println("conn redis failed, err: ", err)
        return
    }

    defer c.Close()

    //set
    _, err = c.Do("SET", "name", "redis-go")
    if err != nil {
        fmt.Println("err")
        return
    }
    //get
    r, err := redis.String(c.Do("GET", "name"))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(r)

    //hset
    _, err = c.Do("HSET", "names", "redis", "hset")
    if err != nil {
        fmt.Println(err)
        return
    }
    //hget
    r, err = redis.String(c.Do("HGET", "names", "redis"))
    if err != nil {
        fmt.Println("hget err: ", err)
        return
    }
    fmt.Println(r)

    //exipres
    _, err = c.Do("expires", "names", 5)
    if err != nil {
        fmt.Println("expire err: ", err)
        return
    }
}

 

2: 管道操作示例
请求/响应服务可以实现持续处理新请求,客户端可以发送多个命令到服务器而无需等待响应,最后在一次读取多个响应。
使用Send(),Flush(),Receive()方法支持管道化操作
Send向连接的输出缓冲中写入命令。
Flush将连接的输出缓冲清空并写入服务器端。
Recevie按照FIFO顺序依次读取服务器的响应

redis_pipline.go

package main

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

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

    c.Send("SET", "name1", "redis001")
    c.Send("SET", "name2", "redis002")
    c.Flush()

    v, err := c.Receive()
    fmt.Printf("v: %v, err: %v \n", v, err)

    v, err = c.Receive()
    fmt.Printf("v: %v, err: %v \n", v, err)

    v, err = c.Receive() // 夯住,一直等待
    fmt.Printf("v:%v,err:%v\n", v, err)
}

 

3: 连接池示例

package main

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

var pool *redis.Pool

func init() {
    pool = &redis.Pool{
        MaxIdle:     20,   //最大的空闲连接数,表示即使没有redis连接时依然可以保持N个空闲的连接,而不被清除,随时处于待命状态
        MaxActive:   120,  //最大的激活连接数,表示同时最多有N个连接
        IdleTimeout: 350,  //最大的空闲连接等待时间,超过此时间后,空闲连接将被关闭
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", "192.168.0.109:6379")
        },
    }
}

func main() {
    client := pool.Get()
    defer client.Close()

    _, err := client.Do("SET", "names", "redis-pool")
    if err != nil {
        fmt.Println("set error: ", err)
        return
    }

    r, err := redis.String(client.Do("GET", "names"))
    if err != nil {
        fmt.Println("get error: ", err)
        return
    }
    fmt.Println(r)
}

 

二: mysql示例


 虽然go的mysql包有很多,比如gorm,xorm, 但是我们使用一个简单的 sqlx(github.com/jmoiron/sqlx)

这里有sqlx的用法 http://jmoiron.github.io/sqlx/

1: 增加
mysql_insert.go

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

var DB *sqlx.DB

type User struct {
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
}

func init() {
    db, err := sqlx.Open("mysql", "root:root@(localhost:3306)/blog")
    if err != nil {
        fmt.Println("open mysql err: ", err)
        return
    }
    DB = db
}

func main() {
    res, err := DB.Exec("INSERT INTO users (name, email, password) VALUES (?, ?, ?)", "mysqldemo", "my@12.com", "111")
    if err != nil {
        fmt.Println("insert err: ", err)
        return
    }
    id, err := res.LastInsertId()
    if err != nil {
        fmt.Println("get last id err: ", err)
        return
    }
    fmt.Println("insert success: ", id)
}


2: 修改
mysql_update.go

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

var DB *sqlx.DB

type User struct {
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
}

func init() {
    db, err := sqlx.Open("mysql", "root:root@(localhost:3306)/blog")
    if err != nil {
        fmt.Println("open mysql err: ", err)
        return
    }
    DB = db
}

func main() {
    _, err := DB.Exec("UPDATE users SET name=? WHERE id=?", "mysqlupdate", 1)
    if err != nil {
        fmt.Println("update err: ", err)
        return
    }
}

 

3:删除
mysql_del.go

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

var DB *sqlx.DB

type User struct {
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
}

func init() {
    db, err := sqlx.Open("mysql", "root:root@(localhost:3306)/blog")
    if err != nil {
        fmt.Println("open mysql err: ", err)
        return
    }
    DB = db
}

func main() {
    _, err := DB.Exec("DELETE FROM users WHERE id = ?", 2)
    if err != nil {
        fmt.Println("del err : ", err)
        return
    }
    fmt.Println("del success")
}

 

4:查询
mysql_select.go

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

var DB *sqlx.DB

type User struct {
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
}

func init() {
    db, err := sqlx.Open("mysql", "root:root@(localhost:3306)/blog")
    if err != nil {
        fmt.Println("open mysql err: ", err)
        return
    }
    DB = db
}

func main() {
    var users []User
    err := DB.Select(&users, "SELECT name, email, password FROM users WHERE id=?", 1)
    if err != nil {
        fmt.Println("select err: ", err)
        return
    }
    fmt.Println("select success: ", users)

    person := []User{}
    DB.Select(&person, "SELECT name,email,password FROM users")
    fmt.Println(person)
}

 

5: 事务
mysql_trans.go

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
    "log"
)

//事务
var DB *sqlx.DB

type User struct {
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
}

func init() {
    db, err := sqlx.Open("mysql", "root:root@(localhost:3306)/blog")
    if err != nil {
        fmt.Println("open mysql err: ", err)
        return
    }
    DB = db
}

func main() {
    tx, err := DB.Begin()
    if err != nil {
        log.Println("DB begin failed err: ", err)
        return
    }

    defer func() {
        if p := recover(); p != nil {
            tx.Rollback()
            panic(p)
        }
    }()
   //这里写一个demo
    if _, err = tx.Exec("INSERT INTO users (name, email, password) VALUES (?, ?, ?)", "demo2", "demo@12.com", "333"); err != nil {
        tx.Rollback()
        return
    }
    if _, err = tx.Exec("INSERT INTO users (name, email, password) VALUES (?, ?, ?)", "demo3", "demo3@12.com", "444"); err != nil {
        tx.Rollback()
        return
    }

    err = tx.Commit()
    return
}

 

posted @ 2017-06-15 20:59  九卷  阅读(1170)  评论(0编辑  收藏  举报