开发者

Golang使用Redis与连接池方式

目录
  • golang使用Redis与连接池
    • redis数据源连接池
  • Golang Redis连接池封装
    • 创建连接池方法文件
    • 配置文件
    • 调用方法
  • 总结

    Golang使用Redis与连接池

    使用下载go的redis包go get github.com/gomodule/redigo/redis 如果网不好的话就很费劲了

    package main
    
    import (
    	"fmt"
    	"github.com/gomodule/redigo/redis" // 引入redis包
    )
    
    func main() {
    	//连接数据源
    	rediss, err := redis.Dial("tcp", "127.0.01:6379")
    
    	if err != nil {
    		fmt.Println("连接异常", err)
    	}
    
    	//插入string数据
    	test, err := rediss.Do("set", "test", "hi")
    	if err != nil {
    		fmt.Println("插入数据失败", err)
    	}
    	fmt.Println(test)
    
    	//读取string数据
    	str, err := redis.String(rediss.Do("get", "test"))
    	fmt.Println(str)
    
    	//hash 类型
    	do, _ := rediss.Do("hset", "hh", "name", "zhangsn")
    	fmt.Println(do)
    	hh, _ := redis.String(rediss.Do("hget", "http://www.devze.comhh", "name"))
    	fmt.Println(hh)
    
    	//设置key 过期时间
    	rediss.Do("expire", "hh", 1)
    
    	//关闭redi编程客栈s
    	rediss.Close()
    }
    
    

    redis数据源连接池

    package main
    
    import (
        "fmt"
        "github.com/gomodule/redigo/redis" // 引入redis包
    )
    
    var pool *redis.Pool
    
    func init() {
        pool = &redis.Pool{
            MaxIdle:     8,   //最大空闲连接数
            MaxActive:   0,   //表示php和数据库最大连接数。0表示没有限制
            IdleTimeout: 100, //最大空闲时间
            Dial: func() (red编程客栈is.Conn, error) { //初始化连接 redis 地址
                return redis.Dial("tcp", "127.0.01:6379")
            },
        }
    }
    func main() {
    
        //获取连接
        conn := pool.Get()
        //插入数据
        do, err := conn.Do("set", "11", "11")
        if err != nil {
            fmt.Println("插入失败", err)
        }
    
        fmt.Println(do)
    
        //关闭redis
        conn.Close()
    
    }

    Golang Redis连接池封装

    创建连接池方法文件

    package dao
     
    import (
    	"fmt"
    	"github.com/gomodule/redigo/redis"
    	"gopkg.in/ini.v1"
    	"os"
    	"sync"
    	"time"
    )
     
    var once sync.Once
     
    // RedisClient Redis 服务
    type RedisClient struct {
    	Client *redis.Pool
    }
     
    //Redis 全局 Redis
    var RedisPool *RedisClient
     
    //ConnectRedis 连接 redis 数据库,设置全局的 Redis 对象
    func ConnectRedis() {
    	config, err := ini.Load("./config/app.ini")
    	if err != nil {
    		//失败
    		fmt.Printf("Fail to read file: %v", err)
    		os.Exit(1)
    	}
    	address := config.Section("redis").Key("address").String()
    	password := config.Section("redis").Key("password").String()
    	db, _ := config.Section("redis").Key("db").Int()
    	once.Do(func() {
    		RedisPool = NewClient(address, password, db)
    	})
    	con_err := RedisPool.Ping()
    	if con_err != nil {
    		panic(con_err)
    	}
    }
     
    // NewClient 创建一个新的 redis 连接
    func NewClient(address string, password string, db int) *RedisClient {
    	// 初始化自定的 RedisClient 实例
    	rds := &RedisClient{}
    	// 使用 redis 库里的 NewClient 初始化连接
    	rds.Client = &redis.Pool{
    		MaxIdle:     100,  //最大空闲
    		MaxActive:   1000, //最大连接
    		IdleTimeout: time.Duration(60) * time.Second,
    		Wait:        true,
    		Dial: func() (redis.Conn, error) {
    			c, err := redis.Dial(
    				"tcp",
    				address,
    				redis.DialPassword(password),
    				redis.DialDatabase(int(db)),
    				redis.DialConnectTimeout(time.Duration(60)*time.Second),
    				redis.DialReadTimeout(time.Duration(60)*time.Second),
    				redis.DialWriteTimeout(time.Duration(60)*time.Second),
    			)
    			if err != nil {
    				return nil, err
    			}
    			return c, err
    		},
    	}
    	return rds
    }
     
    // Ping 用以测试 redis 连接是否正常
    func (rds *RedisClient) Ping() error {
    	_, err := rds.Client.Get().Do("ping")
    	return err
    }
     
    // Set 存储 key 对应的 value,且设置 expiration 过期时间(单位纳秒)
    func (rds *RedisClient) Setex(key string, expiration int, value interface{}) bool {
    	conn := rds.Client.Get()
    	defer conn.Close()
    	if _, err := conn.Do("setex", key, expiration, value); err != nil {
    		fmt.Println(err)
    		return false
    	}
    	return true
    }
     
    //
    //Get 获取 key 对应的 value
    func (rds *RedisClient) Get(key string) string {
    	conn := rds.Client.Get()
    	defer conn.Close()
    	result, err := redis.String(conn.Do("Get", key))
    	if err != nil {
    		return ""
    	}
    	return result
    }
     
    //Get 获取 key 对应的 value
    func (rds *RedisClient) Rpop(key string) (string, error) {
    	conn := rds.Client.Get()
    	defer conn.Close()
    	result, err := redis.String(conn.Do("Rpop", key))
    	if err != nil {
    		return "", err
    	}
    	return result, nil
    }

    配置文件

    app_name   = go-gin
     
     
    [mysql]
    ip       = 127.0.0.1
    port     = 3306
    user     = root
    password = root
    database = test
    prefix   = tt_
    #最大连接数
    MaxIdleConns = 500
    #最大空闲
    MaxOpenConns = 50
     
    [redis]
    address   = 127.0.0.1:6379
    password = 123456
    db = 7

    调用方法

    func main() {
    	dao.ConnectRedis()                 //初始化连接redis
    	defer dao.RedisPool.Client.Close() //退出前执行关闭
    	res, err := dao.RedisPool.Rpop("aaa")
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(res)
    }

    总结

    以上为个人经验编程客栈,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新数据库

    数据库排行榜