golang redis封装工具

1、redistools代码

package redistools

import (
	"github.com/garyburd/redigo/redis"
	"time"
)

type RedisDataStore struct {
	RedisHost string
	RedisDB   string
	RedisPwd  string
	Timeout   int64
	RedisPool *redis.Pool
}

func (r *RedisDataStore) NewPool() *redis.Pool {

	return &redis.Pool{
		Dial:        r.RedisConnect,
		MaxIdle:     10,
		MaxActive:   0,
		IdleTimeout: 1 * time.Second,
		Wait:        true,
	}
}

func (r *RedisDataStore) RedisConnect() (redis.Conn, error) {
	c, err := redis.Dial("tcp", r.RedisHost)
	if err != nil {
		return nil, err
	}
	_, err = c.Do("AUTH", r.RedisPwd)

	if err != nil {
		return nil, err
	}

	_, err = c.Do("SELECT", r.RedisDB)
	if err != nil {
		return nil, err
	}

	redis.DialConnectTimeout(time.Duration(r.Timeout) * time.Second)
	redis.DialReadTimeout(time.Duration(r.Timeout) * time.Second)
	redis.DialWriteTimeout(time.Duration(r.Timeout) * time.Second)

	return c, nil
}

func (r *RedisDataStore) Get(k string) (interface{}, error) {
	c := r.RedisPool.Get()
	defer c.Close()
	v, err := c.Do("GET", k)
	if err != nil {
		return nil, err
	}
	return v, nil
}

func (r *RedisDataStore) Set(k, v string) error {
	c := r.RedisPool.Get()
	defer c.Close()
	_, err := c.Do("SET", k, v)
	return err
}

func (r *RedisDataStore) SetEx(k string, v interface{}, ex int64) error {
	c := r.RedisPool.Get()
	defer c.Close()
	_, err := c.Do("SET", k, v, "EX", ex)
	return err
}

2、redistools_test代码

package redistools_test

import (
	"fmt"
	"gitlab.liquidnetwork.com/box_backend/boxapigo/utils/redistools"
	"testing"
)

var RDSTest redistools.RedisDataStore 

func init(){
	// redis test 库初始化
	RDSTest = redistools.RedisDataStore{
		RedisHost: "127.0.0.1:6379",
		RedisPwd:  "1q2w3e4r",
		RedisDB:   "1",
		Timeout:   20,
		RedisPool: nil,
	}
	RDSTest.RedisPool = RDSTest.NewPool()
}

func TestRedisDataStore_Get(t *testing.T) {
	v, err := RDSTest.Get("testKey")
	if err != nil {
		fmt.Println(v)
	}
}

func TestRedisDataStore_Set(t *testing.T) {
	err := RDSTest.Set("RDSTest", "I am test")
	if err != nil {
		fmt.Println(err)
	}
}

func TestRedisDataStore_SetEx(t *testing.T) {
	err := RDSTest.SetEx("RDSTest", "I am test", 3600)
	if err != nil {
		fmt.Println(err)
	}
}

 

你可能感兴趣的:(golang开发)