golang总结-Redis整合

go get github.com/gomodule/redigo/redis

1. 基本用法

  1. 获取连接
package conn

import (
	"github.com/gomodule/redigo/redis"
	"log"
)

const (
	redis_passwd = ""
	redis_host = ""
	redis_port = ""
	redis_address = "192.168.2.130:6379"
)

func getConn() redis.Conn {
	conn, err := redis.Dial("tcp", redis_address)
	if err != nil {
		log.Println("redis connect err", err)
		panic(err)
	}
	return conn
}
  1. 操作redis
package conn

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"log"
)

var c = getConn()

//string 操作

func Set(key string, value interface{}) bool {
	defer c.Close()
	_, err := c.Do("set", key, value)
	if err != nil {
		log.Println("set a value error,", err)
		return false
	}
	return true
}


func Get(key string) string {
	defer c.Close()
	value, err := redis.String(c.Do("get", key))
	if err != nil {
		log.Println("get a value error,", err)
		return ""
	}

	return value
}

func Del(key string) bool {
	defer c.Close()
	_, err := c.Do("del", key)
	if err != nil {
		log.Println("del a key error, ", err)
		return false
	}
	return true
}

//Hash操作
func HashSet(key string, data map[string]interface{}) {
	defer c.Close()
	for k, v := range data {
		_, err := c.Do("hset", key, k, v)
		if err != nil {
			log.Println("hset a error, ", err)
			continue
		}
	}
}

func HashMGet(key string) map[string]interface{} {
	defer c.Close()

	data := make(map[string]interface{})

	reply, err := redis.ByteSlices(c.Do("hgetall", key))
	if err != nil {
		log.Println("hmget error, ", err)
		return nil
	}
	for i, v := range reply {
		fmt.Println(string(v))
		if i % 2 == 0 {
			data[string(v)] = string(reply[i+1])
		}
		continue
	}
	return data

}

2. Redis连接池

package pool

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

var (
	pool *redis.Pool
)

const (
	redis_host = "192.168.2.130:6379"
)

func init() {
	pool = &redis.Pool{
		MaxIdle: 10,
		MaxActive: 0, //0表示没有限制
		IdleTimeout: 1 * time.Second,
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", redis_host)
		},
	}
}

获取连接:conn := pool.Get()

posted @ 2019-02-08 21:51  小洋编程  阅读(428)  评论(0编辑  收藏  举报