GO连接Reids存取json

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),
				//red.DialPassword(""),
			)
		},
	}
	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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值