GO连接Reids
reids连接池
package utils
import (
"github.com/astaxie/beego"
red "github.com/gomodule/redigo/redis"
"time"
)
type Redis struct {
pool *red.Pool
}
var redis *Redis
func InitRedis() *red.Pool {
host := beego.AppConfig.String("redis_host")
password := beego.AppConfig.String("redis_password")
redis = new(Redis)
redis.pool = &red.Pool{
MaxIdle: 256,
MaxActive: 0,
IdleTimeout: time.Duration(120),
Dial: func() (red.Conn, error) {
return red.Dial(
"tcp",
host,
red.DialPassword(password),
red.DialReadTimeout(time.Duration(1000)*time.Millisecond),
red.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
red.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
red.DialDatabase(0),
)
},
}
return redis.pool
}
Redis存储(二级缓存)
package service
import (
"encoding/json"
"github.com/gomodule/redigo/redis"
"log"
"youblog/mapper"
"youblog/utils"
)
func ListSoftWares() string {
redisConn := utils.InitRedis().Get()
if err := redisConn.Err();err!=nil {
log.Fatal("redis连接出现错误")
}
defer redisConn.Close()
softJson, _ := redis.Bytes(redisConn.Do("get", "json:soft"))
if softJson == nil {
jsonFromDB := getJsonFromDB()
n, err := redisConn.Do("set", "jsonFromDB:soft", jsonFromDB)
if err != nil {
log.Fatal("redis存入string类型失败",err)
}
if n == int64(1) {
log.Fatal("redis存储string类型成功")
}
}
return string(softJson)
}
func getJsonFromDB() string {
listSoftWares := mapper.ListSoftWares()
bytes, err := json.Marshal(listSoftWares)
if err != nil {
log.Fatal("序列化json错误", err.Error())
}
return string(bytes)
}