Golang之redis
redis是个开源的高性能的key-value的内存数据库,可以把它当成远程的数据结构。 支持的value类型非常多,比如string、list(链表)、set(集合)、 hash表等等 redis性能非常高,单机能够达到15w qps,通常适合做缓存。
使用第三方开源的redis库: github.com/garyburd/redigo/redis import( "github.com/garyburd/redigo/redis" )
1、windows安装redis
下载安装 https://github.com/MicrosoftArchive/redis
解压,启动,如下
1
2、linxu安装redis
https://redis.io/download
3、连接redis
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main(){ c,err:=redis.Dial("tcp","127.0.0.1:6379") if err!=nil{ fmt.Println("conn redis failed,",err) return } //fmt.Println("连接成功",c) defer c.Close() }
4、set,get,设置键值,取得键值
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { //p是指针类型int var p *int var a int p = &a //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取值,取int类型的值 r, err := redis.Int(c.Do("Get", "abc")) if err != nil { fmt.Println("get abc failed,", err) return } fmt.Println(r) //从redis取值,取name,string类型的值 r1, err := redis.String(c.Do("Get", "name")) if err != nil { fmt.Println("get abc failed,", err) return } fmt.Println(r1) }
5、hash表设置键值,取键值
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { c, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println("conn redis failed,", err) return } defer c.Close() //设置hash _, err = c.Do("HSet", "books", "abc", 100) if err != nil { fmt.Println(err) return } //取得hash r, err := redis.Int(c.Do("HGet", "books", "abc")) if err != nil { fmt.Println("get abc failed,", err) return } fmt.Println(r) }
6、批量set键值
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { //建立连接 c, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println("conn redis failed,", err) return } defer c.Close() _, err = c.Do("MSet", "abc", 100, "efg", 300) if err != nil { fmt.Println(err) return } r, err := redis.Ints(c.Do("MGet", "abc", "efg")) if err != nil { fmt.Println("get abc failed,", err) return } for _, v := range r { fmt.Println(v) } }
7、设置过期时间
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { c, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println("conn redis failed,", err) } defer c.Close() _, err = c.Do("expire", "abc", 10) if err != nil { fmt.Println(err) return } }
8.list队列操作
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { c, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println("conn redis failed,", err) return } defer c.Close() _, err = c.Do("lpush", "book_list", "abc", "efg", 300) 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) }
9、redis连接池pool
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) //poll是指针 var pool *redis.Pool //初始化执行函数 func init() { pool = &redis.Pool{ MaxIdle: 16, MaxActive: 0, IdleTimeout: 300, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", "127.0.0.1:6379") }, } } func main() { c := pool.Get() defer c.Close() _, err := c.Do("Set", "abc", 100) if err != nil { fmt.Println(err) return } r, err := redis.Int(c.Do("Get", "abc")) if err != nil { fmt.Println("get abc failed,", err) return } fmt.Println(r) pool.Close() }
Golang之Mysql操作
增加insert
package main import ( "fmt" "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" //初始化一个mysql驱动,必须 ) type Person struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { //"mysql"指定数据库类型, /test指定数据库 root:123 冒号隔开密码 root账号 123密码 database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { //插入数据入表 r, err := Db.Exec("insert into person(username,sex,email)values(?,?,?)", "chaoge", "man", "yc_uuu@163.com") if err != nil { fmt.Println("exec failed,", err) return } id, err := r.LastInsertId() if err != nil { fmt.Println("exec failed,", err) return } fmt.Println("insert succ:", id) }
查询select
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person struct { UserId int `db:"user_id"'` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { //初始化链接数据库 database, err := sqlx.Open("mysql", "root:@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed", err) return } Db = database } func main() { var person []Person err := Db.Select(&person, "select user_id,username,sex,email from person where user_id=?", 1) if err != nil { fmt.Println("exec failed,", err) return } fmt.Println("select succ:", person) }
改update
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { _, err := Db.Exec("update person set username=? where user_id=?", "chaoge666", 1) if err != nil { fmt.Println("exec failed,", err) } }
删delete
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { //初始化链接数据库 database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { _, err := Db.Exec("delete FROM person where user_id=?", 1) if err != nil { fmt.Println("exec failed,", err) return } fmt.Println("delete succ") }
Golang之Mysql事务
Mysql事务 1)原子性 2)一致性 3)隔离性 4)持久性
示例代码
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" //初始化一个mysql驱动,必须 "github.com/jmoiron/sqlx" ) type Person struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { //"mysql"指定数据库类型, /test指定打开的数据库 root:123 冒号隔开密码 root账号 123密码 database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { //事务操作 conn, err := Db.Begin() if err != nil { return } //插入数据入表 r, err := Db.Exec("insert into person(username,sex,email)values(?,?,?)", "chaoge", "man", "yc_uuu@163.com") if err != nil { fmt.Println("exec failed,", err) return } id, err := r.LastInsertId() if err != nil { fmt.Println("exec failed,", err) //回滚 conn.Rollback() return } fmt.Println("insert succ:", id)
//提交事务 conn.Commit() }
Golang之http编程
Go原生支持http。import("net/http") Go的http服务性能和nginx比较接近 几行代码就可以实现一个web服务
服务端http
package main import ( "fmt" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprintf(w, "hello") } func Login(w http.ResponseWriter, r *http.Request) { fmt.Println("handle login") fmt.Fprintf(w, "login....") } func main() { http.HandleFunc("/", Hello) http.HandleFunc("/user/login", Login) err := http.ListenAndServe("127.0.0.1:8800", nil) if err != nil { fmt.Println("htpp listen failed") } }
http客户端
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { res, err := http.Get("https://www.baidu.com/") if err != nil { fmt.Println("get err:", err) return } data, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("get data err:", err) return } fmt.Println(string(data)) }
http_head
package main import ( "fmt" "net/http" ) var url = []string{ "http://www.baidu.com", "http://google.com", "http://taobao.com", } func main() { for _, v := range url { res, err := http.Head(v) if err != nil { fmt.Printf("head %s failed,err:%v ", v, err) continue } fmt.Printf("head succ,status:%v ", res.Status) } }
http_head自定义超时写法
package main import ( "fmt" "net" "net/http" "time" ) var url = []string{ "http://www.baidu.com", "http://google.com", "http://taobao.com", } func main() { for _, v := range url { //超时写法 c := http.Client{ Transport: &http.Transport{ Dial: func(network, addr string) (net.Conn, error) { timeout := time.Second * 2 return net.DialTimeout(network, addr, timeout) }, }, } resp, err := c.Head(v) if err != nil { fmt.Printf("head %s failed,err:%v ", v, err) continue } fmt.Printf("head succ,status:%v ", resp.Status) } }
http_form写法
package main
import (
"io"
"log"
"net/http"
)
const form = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></body></html>`
func SimpleServer(w http.ResponseWriter, request *http.Request) {
io.WriteString(w, "hello,world")
panic("test test")
}
func FormServer(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
io.WriteString(w, form)
case "POST":
request.ParseForm()
io.WriteString(w, request.Form["in"][1])
io.WriteString(w, " ")
io.WriteString(w, request.FormValue("in"))
}
}
func main() {
//用函数封装了一下
http.HandleFunc("/test1", logPanics(SimpleServer))
http.HandleFunc("/test2", logPanics(FormServer))
if err := http.ListenAndServe(":8088", nil); err != nil {
}
}
//捕获,错误处理
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(write http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v]caught panic:%v", request.RemoteAddr, x)
}
}()
handle(write, request) //这里才是
}
}
http_template,模板写法
package main import ( "fmt" "os" "text/template" ) type Person struct { Name string age string Title string } func main() { t, err := template.ParseFiles("d:/project/src/go_dev/day10/http_form/index.html") if err != nil { fmt.Println("parse file err:", err) return } p := Person{Name: "Mary", age: "31", Title: "我的个人网站"} if err := t.Execute(os.Stdout, p); err != nil { fmt.Println("There was an error:", err.Error()) } }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{.Title}}</title> </head> <body> <p>hello,{{.Name}}</p> <p>{{.}}</p> </body> </html>
用例2:
package main import ( "fmt" "html/template" "io" "net/http" ) var myTemplate *template.Template type Result struct { output string } func (p *Result) Write(b []byte) (n int, err error) { fmt.Println("called by template") p.output += string(b) return len(b), nil } type Person struct { Name string Title string Age int } func userInfo(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") //fmt.Fprintf(w,"hello") var arr []Person p := Person{Name: "Mary001", Age: 10, Title: "我的网站"} p1 := Person{Name: "Mary002", Age: 10, Title: "我的个人网站"} p2 := Person{Name: "Mary003", Age: 10, Title: "我的网站2"} arr = append(arr, p) arr = append(arr, p1) arr = append(arr, p2) resultWriter := &Result{} io.WriteString(resultWriter, "hello world") err := myTemplate.Execute(w, arr) if err != nil { fmt.Println(err) } fmt.Println("template render data:", resultWriter.output) //myTemplate.Execute(w, p) //myTemplate.Execute(os.Stdout, p) //file, err := os.OpenFile("C:/test.log", os.O_CREATE|os.O_WRONLY, 0755) //if err != nil { // fmt.Println("open failed err:", err) // return //} } func initTemplate(filename string) (err error) { myTemplate, err = template.ParseFiles(filename) if err != nil { fmt.Println("parse file err:", err) return } return } func main() { initTemplate("d:/project/src/go_dev/day10/template_http/index.html") http.HandleFunc("/user/info", userInfo) err := http.ListenAndServe("127.0.0.1:8880", nil) if err != nil { fmt.Println("http listen failed") } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <p>hello world</p> <table border="1"> {{range .}} <tr> <td>{{.Name}}</td> <td>{{.Age}}</td><td>{{.Title}}</td> </tr> {{end}} </table> </body> </html>