wget http://download.redis.io/releases/redis-5.0.3.tar.gz tar xzf redis-5.0.3.tar.gz
mv redis-5.0.3 /usr/local/
cd /usr/local/redis-5.0.3 sudo make test
sudo make install
redis-server
若出現如下畫面則表示redis數據庫已經啓動了:
jpgmysql
數據緩存應該考慮同步問題:若是對數據進行了緩存,當查詢數據時,若是緩存中有數據則直接返回緩存數據不會查詢數據庫,當數據庫數據改變的時候就有可能出現數據庫不一致的問題。能夠考慮在每次修改數據庫的時候同時將對應的緩存數據刪除,這樣從新查詢的時候就會查詢數據庫並緩存git
package redigo_pool import ( "flag" "github.com/garyburd/redigo/redis" "time" ) var ( Pool *redis.Pool RedisServer = flag.String("redisServer", ":6379", "") ) func init() { Pool = &redis.Pool{ MaxIdle: 3, //最大空閒連接數,表示即便沒有redis連接事依然能夠保持N個空閒連接,而不被清除 MaxActive: 3, //最大激活鏈接數,表示同時最多有多少個連接 IdleTimeout: 240 * time.Second,//最大空閒連接等待時間,超過此時間,空閒將被關閉 Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", *RedisServer) if err != nil { return nil, err } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < time.Minute { return nil } _, err := c.Do("PING") return err }, } }
package main import ( "database/sql" "encoding/json" "fmt" "github.com/garyburd/redigo/redis" _ "github.com/go-sql-driver/mysql" "strconv" "web/redis/redigo_pool" _ "web/redis/redigo_pool" ) type Person struct { Id int `db:"id"` Name string `db:"name"` Age int `db:"age"` Rmb int `db:"rmb"` } func main() { var cmd string for{ fmt.Println("輸入命令") fmt.Scan(&cmd) switch cmd { case "getall": getAll() default: fmt.Println("不能識別其餘命令") } fmt.Println() } } func getAll() { //從鏈接池當中獲取連接 conn := redigo_pool.Pool.Get() //先查看redis中是否有數據 //conn,_ :=redis.Dial("tcp","localhost:6379") defer conn.Close() values, _ := redis.Values(conn.Do("lrange", "mlist",0,-1)) if len(values) > 0 { //若是有數據 fmt.Println("從redis獲取數據") //從redis中直接獲取 for _,key := range values{ pid :=string(key.([]byte)) id ,_:= strconv.Atoi(pid) results,_ := redis.Bytes(conn.Do("GET",id)) var p Person err := json.Unmarshal(results,&p) if err != nil { fmt.Println("json 反序列化出錯") }else { fmt.Printf("name = %s\n",p.Name) } } }else { fmt.Println("從mysql中獲取") //查詢數據庫 db,_ := sql.Open("mysql","root:Szt930708@tcp(localhost:3306)/mydb") defer db.Close() var persons []Person rows,_ := db.Query("select id,name,age,rmb from person") for rows.Next() { var id int var name string var age int var rmb int rows.Scan(&id,&name,&age,&rmb) per := Person{id,name,age,rmb} persons = append(persons,per) } //寫入到redis中:將person以hash的方式寫入到redis中 for _,p := range persons{ p_byte,_ := json.Marshal(p) _,err1 := conn.Do("SETNX",p.Id,p_byte) _,err2 := conn.Do("lpush","mlist",p.Id) // 設置過時時間 conn.Do("EXPIRE",p.Id,60*5) if err1 != nil || err2 != nil { fmt.Println("寫入失敗") }else { fmt.Println("寫入成功") } } conn.Do("EXPIRE","mlist",60*5) } }