Share the Redis and MySQL connection pools implemented by Golang, which you can refer directly to the connection pool handle in your project to invoke the corresponding method.
Give me a chestnut:
1 use of MySQL connection pool
(1) Placing mysql.go in the project subdirectory
(2) Import the connection pool handle to the place where it needs to be called DB
(3) Call DB. Query ()
2 Use of Redis connection pooling
(1) Placing redis.go in the project subdirectory
(2) Import the connection pool handle at the point where it needs to be called Cache
(3) Call cache.setstring ("Test_key", "Test_value")
Latest Code Address:
Https://github.com/hopehook/golang-db
Ps:
Welcome to communicate correct, use on the Light Star bar:)
Attachment:
1 MySQL Connection pool code
Package Libimport ("Database/sql" "FMT" "StrConv" "Github.com/arnehormann/sqlinternals/mysqlinternals" _ "github.com/ Go-sql-driver/mysql ") var mysql map[string]string = map[string]string{" host ":" 127.0.0.1:3306 "," Database ":" "," User ":", "Password": "", "Maxopenconns": "0", "Maxidleconns": "0",}type sqlconnpool struct {drivername stri Ngdatasourcename Stringmaxopenconns Int64maxidleconns int64sqldb *sql. DB//Connection pool}var db *sqlconnpoolfunc init () {datasourcename: = FMT. Sprintf ("%s:%[email protected" (%s)/%s ", mysql[" user "], mysql[" password "], mysql[" host "], mysql[" Database "]) Maxopenconns, _: = StrConv. parseint (mysql["Maxopenconns"], ten, up) Maxidleconns, _: = StrConv. parseint (mysql["Maxidleconns"], ten, +) DB = &sqlconnpool{drivername: "MYSQL", Datasourcename:datasourcename, Maxopenconns:maxopenconns,maxidleconns:maxidleconns,}if ERR: = Db.open (); Err! = Nil {panic ("Init db failed")}}//encapsulated connection Pooling method Func (P *sqlconnpool) open () error {var err erRorp. SqlDB, err = sql. Open (P.drivername, P.datasourcename) p.sqldb.setmaxopenconns (int (P.maxopenconns)) P.sqldb.setmaxidleconns (int (p. Maxidleconns)) return Err}func (P *sqlconnpool) Close () error {return p.sqldb.close ()}func (P *sqlconnpool) Query ( Querystr string, args ... interface{}) ([]map[string]interface{}, error) {rows, err: = P.sqldb.query (Querystr, args ...) Defer rows. Close () if err! = nil {return []map[string]interface{}{}, err}//returns the property dictionary columns, err: = Mysqlinternals. Columns (rows)//Get field type Scanargs: = Make ([]interface{}, Len (Columns)) Values: = Make ([]sql. Rawbytes, Len (columns)) for I, _: = Range values {scanargs[i] = &values[i]}rowsmap: = Make ([]map[string]interface{}, 0, ) for rows. Next () {rows. Scan (Scanargs ...) Rowmap: = Make (map[string]interface{}) for I, Value: = Range values {Rowmap[columns[i]. Name ()] = Bytes2realtype (value, Columns[i]. Mysqltype ())}rowsmap = append (Rowsmap, rowmap)}if err = rows. ERR (); Err! = Nil {return []map[string]interface{}{}, Err}return Rowsmap, Nil}func (P *sqlconnpool) execute (sqlstr string, args ... interface{}) (SQL. Result, error) {return p.sqldb.exec (sqlstr, args ...)} Func (P *sqlconnpool) Update (Updatestr string, args ... interface{}) (Int64, error) {result, err: = P.execute (Updatestr, AR GS ...) If err! = Nil {return 0, err}affect, err: = result. Rowsaffected () return affect, Err}func (P *sqlconnpool) Insert (Insertstr string, args ... interface{}) (Int64, error) {ResU LT, Err: = P.execute (Insertstr, args ...) If err! = Nil {return 0, Err}lastid, err: = result. Lastinsertid () return LastID, Err}func (P *sqlconnpool) Delete (Deletestr string, args ... interface{}) (Int64, error) {ResU LT, Err: = P.execute (Deletestr, args ...) If err! = Nil {return 0, err}affect, err: = result. Rowsaffected () return affect, Err}type sqlconntransaction struct {sqltx *sql. TX//Single Transaction connection}////open a transaction func (P *sqlconnpool) Begin () (*sqlconntransaction, error) {var onesqlconntransaction = &sqlco Nntransaction{}var Err Errorif Pingerr: = p.sqldb.ping (); Pingerr = = Nil {OnesqLCONNTRANSACTION.SQLTX, err = P.sqldb.begin ()}return onesqlconntransaction, err}//package method for a single transaction connection func (T * sqlconntransaction) Rollback () error {return t.sqltx.rollback ()}func (t *sqlconntransaction) Commit () error {return T. Sqltx.commit ()}func (t *sqlconntransaction) Query (querystr string, args ... interface{}) ([]map[string]interface{}, Error) {rows, err: = T.sqltx.query (Querystr, args ...) Defer rows. Close () if err! = nil {return []map[string]interface{}{}, err}//returns the property dictionary columns, err: = Mysqlinternals. Columns (rows)//Get field type Scanargs: = Make ([]interface{}, Len (Columns)) Values: = Make ([]sql. Rawbytes, Len (columns)) for I, _: = Range values {scanargs[i] = &values[i]}rowsmap: = Make ([]map[string]interface{}, 0, ) for rows. Next () {rows. Scan (Scanargs ...) Rowmap: = Make (map[string]interface{}) for I, Value: = Range values {Rowmap[columns[i]. Name ()] = Bytes2realtype (value, Columns[i]. Mysqltype ())}rowsmap = append (Rowsmap, rowmap)}if err = rows. ERR (); Err! = Nil {return []map[string]interface{}{}, ERr}return Rowsmap, Nil}func (t *sqlconntransaction) execute (sqlstr string, args ... interface{}) (SQL. Result, error) {return t.sqltx.exec (sqlstr, args ...)} Func (t *sqlconntransaction) Update (Updatestr string, args ... interface{}) (Int64, error) {result, err: = T.execute (Update Str, args ...) If err! = Nil {return 0, err}affect, err: = result. Rowsaffected () return affect, Err}func (t *sqlconntransaction) Insert (Insertstr string, args ... interface{}) (Int64, Error) {result, err: = T.execute (Insertstr, args ...) If err! = Nil {return 0, Err}lastid, err: = result. Lastinsertid () return LastID, Err}func (t *sqlconntransaction) Delete (Deletestr string, args ... interface{}) (Int64, Error) {result, err: = T.execute (Deletestr, args ...) If err! = Nil {return 0, err}affect, err: = result. Rowsaffected () return affect, err}//othersfunc bytes2realtype (src []byte, columntype String) interface{} {srcstr: = Strin G (SRC) var result interface{}switch ColumnType {case "TINYINT": Fallthroughcase "SMALLINT": FALLTHROUGHCASE "INT": Fallthroughcase "BIGINT": result, _ = StrConv. parseint (SRCSTR, ten) Case "CHAR": Fallthroughcase "VARCHAR": Fallthroughcase "BLOB": Fallthroughcase "TIMESTAMP": Fallthroughcase "DATETIME": result = Srcstrcase "FLOAT": Fallthroughcase "DOUBLE": Fallthroughcase "DECIMAL": result, _ = StrConv. Parsefloat (SRCSTR, +) Default:result = Nil}return result}
2 Redis Connection Pool code
Package Libimport ("StrConv" "Time" "Github.com/garyburd/redigo/redis") var redis map[string]string = map[string]string {"Host": "127.0.0.1:6379", "Database": "0", "Password": "", "Maxopenconns": "0", "Maxidleconns": "0",}var Cach E *redisconnpooltype redisconnpool struct {redispool *redis. Pool}func init () {Cache = &redisconnpool{}maxopenconns, _: = StrConv. parseint (redis["Maxopenconns"], ten, up) Maxidleconns, _: = StrConv. parseint (redis["Maxidleconns"], ten, () database, _: = StrConv. parseint (redis["Database"], ten, max) Cache.redispool = Newpool (redis["host"], redis["password"], int (database), int ( Maxopenconns), int (Maxidleconns)) if Cache.redispool = = Nil {Panic ("Init Redis failed! ")}}func newpool (server, password string, database, Maxopenconns, Maxidleconns int) *redis. Pool {return &redis. Pool{maxactive:maxopenconns,//MAX number of Connectionsmaxidle:maxidleconns,idletimeout:10 * time. Second,dial:func () (Redis. Conn, error) {c, err: = Redis. Dial ("TCP", server) if Err! = Nil {return nil, err}if _, Err: = C.do ("AUTH", password); Err! = Nil {c.close () return nil, Err}if _, Err: = C.do ("select", database); Err! = Nil {c.close () return nil, Err}return C, Err},testonborrow:func (c Redis. Conn, T time. Time) Error {_, Err: = C.do ("PING") return err},}}//close Connection pool func (P *redisconnpool) Close () error {err: = P.redispool.close () Return err}//The current database, execute the command func (P *redisconnpool) does (command string, args ... interface{}) (interface{}, error) {conn: = P . Redispool.get () Defer Conn. Close () return Conn. Do (command, args ...)} String (String) func (P *redisconnpool) SetString (key string, Value interface{}) (interface{}, error) {conn: = P.redispool . Get () Defer Conn. Close () return Conn. Do ("SET", key, Value)}func (P *redisconnpool) GetString (Key String) (string, error) {//Get a connection from the connection pool conn: = p.redispool.ge T ()//closed, in fact, not closed, is put back into the pool, that is, the queue, waiting for the next re-defer Conn. Close () return Redis. String (Conn. Do ("GET", Key))}func (P *redisconnpool) GetBytes (key String) ([]byte, error) {conn: = P.rediSpool.get () Defer Conn. Close () return Redis. Bytes (Conn. Do ("GET", Key))}func (P *redisconnpool) GetInt (key string) (int, error) {conn: = P.redispool.get () defer Conn. Close () return Redis. INT (Conn. Do ("GET", Key))}func (P *redisconnpool) GetInt64 (key string) (Int64, error) {conn: = P.redispool.get () defer Conn. Close () return Redis. Int64 (Conn. Do ("GET", key))}////key (Key) func (P *redisconnpool) Delkey (Key String) (interface{}, error) {conn: = P.redispool.get () defe R Conn. Close () return Conn. Do ("DEL", Key)}func (P *redisconnpool) Expirekey (key string, seconds Int64) (interface{}, error) {conn: = P.redispool.get ( ) Defer Conn. Close () return Conn. Do ("EXPIRE", key, Seconds)}func (P *redisconnpool) Keys (Pattern string) ([]string, error) {conn: = P.redispool.get () defer Conn. Close () return Redis. Strings (Conn. Do ("KEYS", pattern))}func (P *redisconnpool) keysbyteslices (Pattern string) ([][]byte, error) {conn: = P.redispool.get () Defer Conn. Close () return Redis. Byteslices (Conn. Do ("KEYS", pattern))}////hash (hash table) funC (P *redisconnpool) Sethashmap (key string, Fieldvalue map[string]interface{}) (interface{}, error) {conn: = P.redispool. Get () Defer Conn. Close () return Conn. Do ("Hmset", Redis.) args{}. ADD (Key). Addflat (Fieldvalue)} Func (P *redisconnpool) gethashmapstring (Key string) (Map[string]string, error) {conn: = P.redispool.get () defer Conn. Close () return Redis. STRINGMAP (Conn. Do ("Hgetall", Key))}func (P *redisconnpool) gethashmapint (Key string) (Map[string]int, error) {conn: = P.redispool.get () Defer Conn. Close () return Redis. INTMAP (Conn. Do ("Hgetall", Key))}func (P *redisconnpool) GetHashMapInt64 (Key string) (Map[string]int64, error) {conn: = P.redispool.get () Defer Conn. Close () return Redis. INT64MAP (Conn. Do ("Hgetall", Key)}
Golang implementation of the Redis MySQL connection pool