因为之前做的一个小网盘想实现一个分片上传,就尝试用了redis,对redis有了一些了解,具体可见:

Redis基础知识:https://blog.csdn.net/Lazyboy_/article/details/88819755

Redis基本操作:https://blog.csdn.net/Lazyboy_/article/details/88821948

现在要使用go语言对redis进行操作就要使用go的一些方法来实现了。


在golang中使用redis还是要站在前辈的肩膀上,用人家的库来实现操作。

import "github.com/garyburd/redigo/redis"

连接

conn接口是使用redis的主要接口。应用程序通过调用dial、dialwithTimeout或newconn函数来创建连接。将来,将添加用于创建分片连接和其他类型连接的功能。

当应用程序完成连接时,应用程序必须调用连接关闭方法。

type Conn interface {// Close closes the connection.Close() error// Err returns a non-nil value when the connection is not usable.Err() error// Do sends a command to the server and returns the received reply.Do(commandName string, args ...interface{}) (reply interface{}, err error)// Send writes the command to the client's output buffer.Send(commandName string, args ...interface{}) error// Flush flushes the output buffer to the Redis server.Flush() error// Receive receives a single reply from the Redis serverReceive() (reply interface{}, err error)
}// 使用指定的选项连接到给定网络和地址的Redis服务器。
func Dial(network, address string, options ...DialOption) (Conn, error)
var (redisHost = "127.0.0.1:6379"redisPass = "1234"
)func main() {c,err := redis.Dial("tcp", redisHost)if err != nil {fmt.Println(err.Error())return}defer c.Close()// 这里因为我设置了密码,所以要连接必须得使用Do方法输入密码if _,err := c.Do("AUTH", redisPass); err != nil {fmt.Println(err.Error())return}
}

执行命令

conn接口具有执行redis命令的通用方法:

Do(commandName string, args ...interface{}) (reply interface{}, err error)

http://redis.io/commands 列出了可用的命令

do方法将命令参数转换为大容量字符串,以便传输到服务器,如上图中传递密码的Do方法。

redis的所有命令操作都可以通过Do方法来实现,只是args的数量问题。

我们通过连接redis执行对string的set和get操作,并设置超时时间。

package mainimport ("fmt""time""github.com/garyburd/redigo/redis"
)var (redisHost = "127.0.0.1:6379"redisPass = "1234"
)func main() {c,err := redis.Dial("tcp", redisHost)if err != nil {fmt.Println(err.Error())return}defer c.Close()if _,err := c.Do("AUTH", redisPass); err != nil {fmt.Println(err.Error())return}_, err = c.Do("SET", "name", "lazyboy", "EX", "5")if err != nil {fmt.Println("redis set failed:", err)}/*  也可以通过下面这段函数为key设置超时时间_, err = c.Do("expire", "name", 10) //10秒过期if err != nil {fmt.Println("set expire error: ", err)return}*/username, err := redis.String(c.Do("GET", "name"))if err != nil {fmt.Println("redis get failed:", err)} else {fmt.Printf("Get name: %v \n", username)}time.Sleep(8 * time.Second)username, err = redis.String(c.Do("GET", "name"))if err != nil {fmt.Println("redis get failed:", err)} else {fmt.Printf("Get name: %v \n", username)}
}

这里可能返回多个值或不能直接使用的值,但是都是存在一个变量中,需要通过一些类型转换、反射等操作得到需要的正确类型值。

Pool连接池

type Pool struct {// Dial is an application supplied function for creating and configuring a// connection.//// The connection returned from Dial must not be in a special state// (subscribed to pubsub channel, transaction started, ...).Dial func() (Conn, error)      //连接                                  {}// TestOnBorrow is an optional application supplied function for checking// the health of an idle connection before the connection is used again by// the application. Argument t is the time that the connection was returned// to the pool. If the function returns an error, then the connection is// closed.TestOnBorrow func(c Conn, t time.Time) error                        {}// Maximum number of idle connections in the pool.MaxIdle int        // 最大空闲连接数// Maximum number of connections allocated by the pool at a given time.// When zero, there is no limit on the number of connections in the pool.MaxActive int      // 最大激活连接数// Close connections after remaining idle for this duration. If the value// is zero, then idle connections are not closed. Applications should set// the timeout to a value less than the server's timeout.IdleTimeout time.Duration    // 空闲连接等待超时时间// If Wait is true and the pool is at the MaxActive limit, then Get() waits// for a connection to be returned to the pool before returning.Wait bool    // 当配置项为true并且MaxActive参数有限制时候,使用Get方法等待一个连接返回给连接池// Close connections older than this duration. If the value is zero, then// the pool does not close connections based on age.MaxConnLifetime time.Duration// contains filtered or unexported fields
}

Pool维护了一个连接池, 应用程序调用Get()方法从池中获取连接,并调用连接的close方法将连接的资源返回池。

func NewPool(newFn func() (Conn, error), maxIdle int) *Pool // 返回一个连接池 {}
func (p *Pool) ActiveCount() int                            // 返回池中链接的个数 {}
func (p *Pool) Close() error                                // 关闭连接池释放资源 {}
func (p *Pool) Get() Conn                                   // 获取连接conn    {}
func (p *Pool) GetContext(ctx context.Context) (Conn, error)// 根据context获取连接 {}
func (p *Pool) IdleCount() int                              // 返回空闲连接数    {}
func (p *Pool) Stats() PoolStats                            // 返回pool的统计信息 {}

举个栗子:

redis.Pool{MaxIdle : 50,MaxActive : 30,IdleTimeout : 300*time.Second,Dial: func() (redis.Conn, error) {//1. 打开连接c,err := redis.Dial("tcp", redisHost)if err != nil {fmt.Println(err)return nil, err}//2. 访问认证if _,err := c.Do("AUTH",redisPass); err != nil {c.Close()return nil, err}return c, nil},TestOnBorrow: func(conn redis.Conn, t time.Time) error {if time.Since(t) < time.Minute {return nil}_,err := conn.Do("PING")return err},
}
rConn := redis.Pool.Get()
defer rConn.Close()

这个是从我的程序中截的一节,上边的初始化是放在一个函数中的,为了方便阅读直接拿出来,下面两行是连接池的连接Get()方法,和释放连接Close()。

Redigo还有更多关于Redis的操作,暂时没有操作经验,先留着以后填坑。

参考资料:

1. https://godoc.org/github.com/garyburd/redigo/redis#Conn

2. https://blog.csdn.net/wangshubo1989/article/details/75050024


记录每天解决的小问题,积累起来去解决大问题。

Golang学习——使用Redis相关推荐

  1. golang学习笔记

    基础知识 驼峰命名法 骆驼式命名法就是当变量名或函数名是由一个或多个单词连结在一起,而构成的唯一识别字时,第一个单词以小写字母开始:从第二个单词开始以后的每个单词的首字母都采用大写字母,例如:myFi ...

  2. Golang学习-基础命令

    链客,专为开发者而生,有问必答! 此文章来自区块链技术社区,未经允许拒绝转载. . Golang学习-基础命令 一.go run 用于运行命令源码文件,只能接收一个命令源码文件以及若干个库源码文件作为 ...

  3. Redis学习笔记~Redis在windows环境下的安装

    Redis是一个key-value的存储系统,它最大的特点就是可以将数据序列化到文件中. redis存储在服务器的内存或者文件中,它不是session,不是cookies,它只是个更安全,更稳定,更可 ...

  4. c++服务器开发学习--02--MySQL,Redis,ASIO,iocp,TrinityCore代码结构,c++对象模型

    c++服务器开发学习--02--MySQL,Redis,ASIO,iocp,TrinityCore代码结构,c++对象模型 MySQL 问题 Redis Asio iocp TrinityCore代码 ...

  5. Go实战--golang中使用redis(redigo和go-redis/redis这个已测试)

    自己做测试了没有问题,虚拟机连不上可以把包下载到本地. 版权声明:本文为博主原创文章,未经博主允许不得转载. http://blog.csdn.net/wangshubo1989/article/de ...

  6. golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题

    golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题 今天测试了重新建一个项目生成新的表,然后复制到旧的项目 ...

  7. Golang学习(10)——bufio包

    Golang学习 - bufio 包 ------------------------------------------------------------ // bufio 包实现了带缓存的 I/ ...

  8. Golang学习(12)——regex包

    Golang学习 - regexp 包 ------------------------ // 函数 // 判断在 b(s.r)中能否找到 pattern 所匹配的字符串 func Match(pat ...

  9. Duang~ Golang 学习初探

    Duang~  Golang学习初步体验,一直以来都对Go语言有一定的喜感,今天花了点时间初步的了解了下Go,其实很多东西弄个小例子go run下会明白很多东西的. 本人开发工具使用的是GoSubli ...

  10. golang学习笔记(五):数组的定义和使用

    golang 学习笔记 数组定义 数组是一系列相同数据类型在内存中有序存储的数据集合 var 数组名 [元素个数]数据类型//定义了10个整型变量的数组元素var arr [10]int//通过下标找 ...

最新文章

  1. 【OpenGL】关于OpenGL中Bind函数的理解
  2. Linux下集群技术应用概述
  3. Tomcat SVN
  4. python行转列_pandas.DataFrame中pivot()如何实现行转列的问题(代码)
  5. Elasticsearch技术解析与实战(四)shardreplica机制
  6. Codeforces Round #674 (Div. 3)
  7. 算法—振兴中华(C语言版)
  8. (十五)nodejs循序渐进-高性能游戏服务器框架pomelo之Protobuf模块
  9. 云重磅|中西合璧 联想凌拓瓜熟蒂落;5G实锤 华为推出首部5G折叠手机;​IBM打造Kubernetes无处不在”的模式...
  10. 如何用Pygame写游戏(二十一)
  11. netbsd配置gnome桌面
  12. AGV车载控制系统搭建(初学者入门)
  13. mov和mp4格式哪个好_Mac版dvd格式转换器哪个好用?Mac上最好用的dvd格式转换器推荐...
  14. 桌面图标有蓝底处理刚才
  15. JVM 宋红康版 : JVM与Java体系结构
  16. JS——数组中去除空空字符串
  17. 项目团队研发人员离职,如何做好交接?| 每天成就更大成功
  18. 计算机应用模块等级考试大纲,全国计算机等级考试大纲 年版.doc
  19. BAT脚本打开重复打开软件
  20. lisp写标高线_cad自动写标高lisp

热门文章

  1. 【行业视角】是什么让元宇宙土地与房产变得有价值
  2. svg 组件用法 -- defs标签使用
  3. Chrome浏览器主页被hao123、360和2345篡改恢复到默认的方法
  4. 计算机术语 谢谢,计算机术语中的TPS是什么意思
  5. Putnam竞赛一道题及中科大自主招生试题的联系
  6. 【读书笔记】你离考研成功就差这本书
  7. php 支付宝验签失败,支付宝移动支付,服务端对异步通知信息验签的时候验签失败...
  8. java提现功能开发_利用java实现提现金额到支付宝账户的功能
  9. 什么是域名系统 (DNS)
  10. linux sed尾行符号,Linux Sed命令学习笔记