首先连接: 创建services/redis 文件夹 , 创建redis.go 文件
package redisClient
import (
"github.com/garyburd/redigo/redis"
"time"
)
// 直接连接
func Connect() redis.Conn {
pool, _ := redis.Dial("tcp", "127.0.0.1:6379")
return pool
}
// 连接池连接
func PoolConnect() redis.Conn {
pool := &redis.Pool{
MaxIdle: 1, //最大空闲连接数
MaxActive: 10, // 最大连接数
IdleTimeout: 180 * time.Second, //空闲连接超时时间
Wait: true, // 超过最大连接数的操作:等待
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
return c, nil
},
}
return pool.Get()
}
使用redis
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/garyburd/redigo/redis"
redisClient "youku/services/redis"
)
type RedisController struct {
beego.Controller
}
// @router /redis/demo [*]
func (this *RedisController) RedisDemo() {
c := redisClient.PoolConnect()
defer c.Close()
_, err := c.Do("SET", "username", "123")
if err != nil {
}
// 设置过期时间
c.Do("expire", "username", 3000)
// 获取
username, err := redis.String(c.Do("get", "username"))
if err == nil {
fmt.Println(username)
// 剩余过期时间
ttl, err := redis.Int64(c.Do("ttl", "username"))
fmt.Println(ttl)
fmt.Println(err)
}
fmt.Println(3)
fmt.Println(err)
this.Ctx.WriteString("123456")
}
改造demo
type Video struct {
Id int
Title string
SubTitle string
AddTime int64
Img string
Img1 string
EpisodesCount int
IsEnd int
ChannelId int
Status int
RegionId int
TypeId int
EpisodesUpdateTime int64
Comment int
UserId int
IsRecommend int
}
// 获取视频详情
func GetVideoInfo(videoId int) (Video, error) {
o := orm.NewOrm()
var video Video
err := o.Raw("select * from video where id=? limit 1", videoId).QueryRow(&video)
return video, err
}
// redis缓存-获取视频详情
func RedisGetVideoInfo(videoId int) (Video, error) {
var video Video
conn := redisClient.PoolConnect()
defer conn.Close()
redisKey := "video:id:" + strconv.Itoa(videoId)
// 判断redis是否存在
exists, err := redis.Bool(conn.Do("exists", redisKey))
if exists {
// redis读取
res, _ := redis.Values(conn.Do("hgetall", redisKey))
err = redis.ScanStruct(res, &video)
} else {
// 数据库读取
o := orm.NewOrm()
err := o.Raw("select * from video where id=? limit 1", videoId).QueryRow(&video)
if err == nil {
//保存redis
_, err := conn.Do("hmset", redis.Args{redisKey}.AddFlat(video)...) //redigo 提供的函数转化struct存到redis中
if err == nil {
// 设置过期时间 1 day
conn.Do("expire", redisKey, 86400)
}
}
}
return video, err
}
本文介绍了如何在Go语言中实现Redis连接,包括直接连接和连接池的方式,并展示了如何利用Redis进行缓存操作,特别是在视频详情获取上,通过Redis缓存提高效率,减少了对数据库的直接查询。当Redis中不存在所需数据时,从数据库读取并保存到Redis,同时设置了数据过期时间。

2348

被折叠的 条评论
为什么被折叠?



