From 91e261dd9bf048ef392967a6e5578cbc4cae8ea1 Mon Sep 17 00:00:00 2001 From: romber Date: Thu, 21 Jan 2021 17:32:01 +0800 Subject: [PATCH] 1. add PoolConn and Pool interface --- middleware/mysql/pool.go | 12 +++++++++++- middleware/pool.go | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 middleware/pool.go diff --git a/middleware/mysql/pool.go b/middleware/mysql/pool.go index 5362aef..f44e122 100644 --- a/middleware/mysql/pool.go +++ b/middleware/mysql/pool.go @@ -10,6 +10,7 @@ import ( "github.com/romberli/log" "github.com/romberli/go-util/constant" + "github.com/romberli/go-util/middleware" ) const ( @@ -22,6 +23,9 @@ const ( DefaultSleepTime = 1 // Seconds ) +var _ middleware.PoolConn = (*PoolConn)(nil) +var _ middleware.Pool = (*Pool)(nil) + type PoolConfig struct { Config MaxConnections int @@ -150,6 +154,10 @@ func (pc *PoolConn) IsValid() bool { return pc.CheckInstanceStatus() } +func (pc *PoolConn) Execute(command string, args ...interface{}) (interface{}, error) { + return pc.Conn.Execute(command, args...) +} + type Pool struct { sync.Mutex PoolConfig @@ -281,7 +289,7 @@ func (p *Pool) addToFreeChan(pc *PoolConn) { } // Get is an exported alias of get() function with routine safe -func (p *Pool) Get() (*PoolConn, error) { +func (p *Pool) Get() (middleware.PoolConn, error) { p.Lock() defer p.Unlock() @@ -378,6 +386,8 @@ func (p *Pool) maintainFreeChan() { } } +// keepAlive keeps alive given number of connections in the pool to avoid disconnected by server side automatically, +// it also checks if connections are still valid func (p *Pool) keepAlive(num int) error { if len(p.freeConnChan) == 0 { return nil diff --git a/middleware/pool.go b/middleware/pool.go new file mode 100644 index 0000000..c4b1083 --- /dev/null +++ b/middleware/pool.go @@ -0,0 +1,16 @@ +package middleware + +type PoolConn interface { + Close() error + DisConnect() error + IsValid() bool + Execute(command string, args ...interface{}) (interface{}, error) +} + +type Pool interface { + Close() error + IsClosed() bool + Get() (PoolConn, error) + Supply(num int) error + Release(num int) error +}