• go-redis


    go-redis初始化

    1.创建连接池

    import "github.com/gomodule/redigo/redis"
    
    var RedisPool *redis.Pool
    
    func init() {
    
    	RedisPool = &redis.Pool{
    		MaxIdle:     5,                 // idle的列表长度, 空闲的线程数
    		MaxActive:   0,                 // 线程池的最大连接数, 0表示没有限制
    		Wait:        true,              // 当连接数已满,是否要阻塞等待获取连接。false表示不等待,直接返回错误。
    		IdleTimeout: 200 * time.Second, //最大的空闲连接等待时间,超过此时间后,空闲连接将被关闭
    		Dial: func() (redis.Conn, error) { // 创建链接
    			c, err := redis.Dial("tcp", beego.AppConfig.String("redis_addr"))
    			if err != nil {
    				return nil, err
    			}
    			if _, err := c.Do("AUTH", beego.AppConfig.String("redis_password")); err != nil {
    				c.Close()
    				return nil, err
    			}
    			if _, err := c.Do("SELECT", beego.AppConfig.String("redis_index")); err != nil {
    				c.Close()
    				return nil, err
    			}
    			return c, nil
    		},
    		TestOnBorrow: func(c redis.Conn, t time.Time) error { //一个测试链接可用性
    			if time.Since(t) < time.Minute {
    				return nil
    			}
    			_, err := c.Do("PING")
    			return err
    		},
    	}
    	//fmt.Println("Redis init on port ", beego.AppConfig.String("redis_addr"))
    }
    

    2.RedisPool简单使用

    // get
    func GetKey(key string) (string, error) {
    	rds := RedisPool.Get()
    	defer rds.Close()
    	return redis.String(rds.Do("GET", key))
    }
    
    // set expires为0时,表示永久性存储
    func SetKey(key, value interface{}, expires int) error {
    	rds := RedisPool.Get()
    	defer rds.Close()
    	if expires == 0 {
    		_, err := rds.Do("SET", key, value)
    		return err
    	} else {
    		_, err := rds.Do("SETEX", key, expires, value)
    		return err
    	}
    }
    
  • 相关阅读:
    当tp5项目上传到服务器之后遇见的各种bug(不定期更新)
    解决LAMP下 服务器IP无法访问
    thinkphp5多图上传+同时删除本地文件
    from提交表单后 数据提交到后台 但不跳转页面 非ajax 用iframe
    window7 安装sass和compass
    开源操作系统课程设计
    Hadoop伪分布式搭建实验总结
    排序集合
    快排
    邻接矩阵
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/12915208.html
Copyright © 2020-2023  润新知