redigo连接池的使用
文章目录
前言
最近使用redigo的时候遇到了并发问题,于是想起了redigo并发是否存在安全性的问题,查了下源码,发现可以用连接池解决,简单介绍一下。
conn
redigo实现了不止一种的Conn对象,一般初次使用,会用redis.Dial()获取一条连接对象。
它是在conn.go中定义的对象。
// conn is the low-level implementation of Conn
type conn struct {
// Shared
mu sync.Mutex
pending int
err error
conn net.Conn
// Read
readTimeout time.Duration
br *bufio.Reader
// Write
writeTimeout time.Duration
bw *bufio.Writer
// Scratch space for formatting argument length.
// '*' or '$', length, "\r\n"
lenScratch [32]byte
// Scratch space for formatting integers and floats.
numScratch [40]byte
}
它实际上是一种低水平的实现,在遇到多协程需要并发操作时是不能用它的 :
![[外链图片转存失败(img-nrxuA0pv-1563279188074)(./1563275388184.png)]](https://i-blog.csdnimg.cn/blog_migrate/d197f0e5039f2b31a4144f772a72155e.png)
连接池
连接池其实就是一种线程池模型,预先开辟并申请一定数量的资源放在池子中,用的时候取一条出来,用完在放回去。
不清楚线程池的可以看看我以前写的c++实现的线程池文章了解下。
接着看看pool,pool的Get()方法可以获取一条Conn对象,它是activeConn对象,不同于上面的conn,它也实现了Conn接口。
// NewPool creates a new pool.
//
// Deprecated: Initialize the Pool directory as shown in the example.
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
return &Pool{
Dial: newFn, MaxIdle: maxIdle}
}
// Get gets a connection. The application must close the returned connection.
// This method always returns a valid connection so that applications can defer
// error handling to the first use of the connection. If there is an error
// getting an underlying connection, then the connection Err, Do, Send, Flush
// and Receive methods return that error.
func (p *Pool) Get() Conn {
pc, err := p.get(nil)
if err != nil {
return errorConn{
err}
}
return &activeConn{
p: p, pc: pc}
}
// Close releases the resources used by the pool.
func (p *Pool) Close() error {
...

本文介绍了使用Redigo连接池解决并发问题的方法,并通过实例演示如何配置连接池参数及并发访问Redis的操作。
最低0.47元/天 解锁文章
1095

被折叠的 条评论
为什么被折叠?



