码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言操作redis

时间:2015-03-05 22:21:08      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:redis   redigo   go语言   

       Redis的Go语言驱动已经很成熟了,用redigo弄了个例子。

package main 

//Redis测试
//author:Xiong Chuan Liang
//date:2015-3-5

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

func main(){
	fmt.Println("Redis:")
	conn,err := redisConn("","","6");
	if err != nil {
		log.Fatal("Error: ", err)
	}
	test(conn)
}

func test(conn *RedisConn) {
	conn.Do("SET","xxx",1)
	if xxx,err :=redis.Int(conn.Do("GET","xxx")); err == nil {
		fmt.Println("xxx:",xxx)
	}

	conn.FlushClose()
}

////////////////////////////////////////////////////////////////
type RedisConn struct {
	dbid string
	redis.Conn
}

func (r *RedisConn)FlushClose() error {
	_, err := r.Conn.Do("SELECT", r.dbid)
	if err != nil {
		return nil
	}
	_, err = r.Conn.Do("FLUSHDB")
	if err != nil {
		return err
	}
	return r.Conn.Close()
}

func (r *RedisConn)Close() error {	
	return r.Conn.Close()
}

func redisConn(host,password,db string) (*RedisConn, error) {
	if host == "" {
		host =  ":6379"
	}
	//conn, err := redis.Dial( "tcp", host)
	conn , err := redis.DialTimeout("tcp", host, 0, 1*time.Second, 1*time.Second)
	if err != nil {
		return nil, err
	}

	if password != "" {
		if _, err := conn.Do("AUTH", password); err != nil {		
			conn.Close()
			return nil, err
		}
	}

	if db != "" {
		if _, err := conn.Do("SELECT", db);err != nil {	
			conn.Close()
			return nil, err
		}
	}

	return &RedisConn{dbid:db,Conn: conn}, nil
}
 可以看到使用非常方便。

MAIL:xcl_168@aliyun.com

BLOG:http://blogcsdn.net/xcl168

Go语言操作redis

标签:redis   redigo   go语言   

原文地址:http://blog.csdn.net/xcl168/article/details/44084329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!