Golang中使用redis

使用Redis:

使用redis进程池,减少与redis-server 的 socket 连接,直接上代码:

package redis
import (
	"github.com/garyburd/redigo/redis"
	"github.com/astaxie/beego"
	"time"
	"fmt"
)

var (
	// 定义常量
	RedisClient     *redis.Pool
	REDIS_HOST string
	REDIS_DB   int
)

func init() {
	// 从配置文件获取redis的ip以及db
	REDIS_HOST := beego.AppConfig.String("prod::REDIS_HOST")
	REDIS_DB, _ = beego.AppConfig.Int("prod::REDIS_DB")
	// 建立连接池
	RedisClient = &redis.Pool{
		// 从配置文件获取maxidle以及maxactive,取不到则用后面的默认值
		MaxIdle:     1,
		MaxActive:   10,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", REDIS_HOST)
		if err != nil {
			return nil, err
		}
		// Auth 有密码的话需要做认证哦~
		c.Do("AUTH","密码")

		// 选择db
		c.Do("SELECT", REDIS_DB)
			return c, nil
		},
	}
}


// 增加某张照片点赞Inc;增加照片点赞用户列表;增加用户喜欢的照片列表;管道操作
func IncPhotoLike(photoId string,uid string)  {
	rc := RedisClient.Get()
	defer  rc.Close()

	photoCount := "PhotoLikeCount" + photoId
	photoSet := "PhotoLike" + photoId
	userLikeSet := "UserLikePhoto"+ uid
	rc.Send("INCR",photoCount)
	rc.Send("SADD",photoSet,uid)
	rc.Send("SADD",userLikeSet,photoId)

	rc.Flush()
	v,err := rc.Receive()
	if err!=nil {
		panic(err)
	}
	fmt.Println("INCR",v)
}


// 获取某用户喜欢过的所有照片
func GetUserLikeSet(uid string) (result string) {
	rc := RedisClient.Get()
	defer  rc.Close()
	res,err := redis.Values(rc.Do("SMEMBERS","UserLikePhoto"+uid))
	if err!=nil {
		panic(nil)
	}

	resStr := ""
	for _, v := range res {
		fmt.Printf("%s ", v.([]byte))
		resStr += string(v.([]byte))+","
	}
	return  resStr
}



// 查看用户是否喜欢这张照片
func IsUserLikePhoto(uid string,Pid string) (IsLike int64) {
	rc := RedisClient.Get()
	defer  rc.Close()
	res,err := rc.Do("SISMEMBER","UserLikePhoto"+uid,Pid)
	if err!=nil {
		panic(nil)
	}
	return res.(int64)
}


使用管道提交

不使用管道提交
rc := RedisClient.Get()
	defer  rc.Close()

	currentTimeStart := time.Now()


	for  i:=0 ;i<100000;i++{
		fmt.Println(i)
		rc.Do("INCR","TESTKEY")
	}

	currentTimeEnd := time.Now()
	fmt.Println(currentTimeStart)
	fmt.Println(currentTimeEnd)
999
2018-12-11 10:56:39.631781548 +0800 CST m=+5.762551128
2018-12-11 10:56:39.731172184 +0800 CST m=+5.861938782
9999
2018-12-11 10:57:48.648119563 +0800 CST m=+2.779452059
2018-12-11 10:57:49.664007439 +0800 CST m=+3.795309460
99999
2018-12-11 10:58:15.006840374 +0800 CST m=+3.051498224
2018-12-11 10:58:23.793490127 +0800 CST m=+11.837884394

管道

func TestPipline()  {

	rc := RedisClient.Get()
	defer  rc.Close()

	currentTimeStart := time.Now()


	for  i:=0 ;i<100000;i++{
		fmt.Println(i)
		rc.Send("INCR","TESTKEY")


	}
	rc.Flush()
	rc.Receive()

	currentTimeEnd := time.Now()
	fmt.Println(currentTimeStart)
	fmt.Println(currentTimeEnd)

}

99999
2018-12-11 11:03:09.416745233 +0800 CST m=+11.625497498
2018-12-11 11:03:09.962783858 +0800 CST m=+12.171518442

可以看到10w次,管道提交只要0.5s ,非管道提交长达8s ,在一些多任务的业务中,可以使用管理来减少时间


领取优惠券
Golang中使用redis_第1张图片

你可能感兴趣的:(Go)