golang 连接池 php,【整理】golang mgo连接池实现 | 勤奋的小青蛙

由于mgo连接池是自带的,你只需要使用session.Copy()拿到一个复制的session,用完之后session.Close()即可。

代码实现如下:

package db

import (

"labix.org/v2/mgo"

// "labix.org/v2/mgo/bson"

)

const (

USER string = "user"

MSG string = "msg"

)

var (

session *mgo.Session

databaseName = "test"

)

func Session() *mgo.Session {

if session == nil {

var err error

session, err = mgo.Dial("localhost")

if err != nil {

panic(err) // no, not really

}

}

return session.Clone()

}

func M(collection string, f func(*mgo.Collection)) {

session := Session()

defer func() {

session.Close()

if err := recover(); err != nil {

Log("M", err)

}

}()

c := session.DB(databaseName).C(collection)

f(c)

}

使用方式:

var m = M{}

db.M(db.USER, func(c *mgo.Collection) {

c.Find(M{"_id": id}).One(m)

Log("find one m", m, m["name"], m["img"])

})

该博客中所写的内容,其实大家在使用mgo的连接用完注意close掉即可避免上文中的堵塞问题。

// This program provides a sample application for using MongoDB with

// the mgo driver.

package main

import (

"labix.org/v2/mgo"

"labix.org/v2/mgo/bson"

"log"

"sync"

"time"

)

const (

MongoDBHosts = "ds035428.mongolab.com:35428"

AuthDatabase = "goinggo"

AuthUserName = "guest"

AuthPassword = "welcome"

TestDatabase = "goinggo"

)

type (

// BuoyCondition contains information for an individual station.

BuoyCondition struct {

WindSpeed float64 `bson:"wind_speed_milehour"`

WindDirection int `bson:"wind_direction_degnorth"`

WindGust float64 `bson:"gust_wind_speed_milehour"`

}

// BuoyLocation contains the buoy's location.

BuoyLocation struct {

Type string `bson:"type"`

Coordinates []float64 `bson:"coordinates"`

}

// BuoyStation contains information for an individual station.

BuoyStation struct {

ID bson.ObjectId `bson:"_id,omitempty"`

StationId string `bson:"station_id"`

Name string `bson:"name"`

LocDesc string `bson:"location_desc"`

Condition BuoyCondition `bson:"condition"`

Location BuoyLocation `bson:"location"`

}

)

// main is the entry point for the application.

func main() {

// We need this object to establish a session to our MongoDB.

mongoDBDialInfo := &mgo.DialInfo{

Addrs: []string{MongoDBHosts},

Timeout: 60 * time.Second,

Database: AuthDatabase,

Username: AuthUserName,

Password: AuthPassword,

}

// Create a session which maintains a pool of socket connections

// to our MongoDB.

mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)

if err != nil {

log.Fatalf("CreateSession: %s\n", err)

}

// Reads may not be entirely up-to-date, but they will always see the

// history of changes moving forward, the data read will be consistent

// across sequential queries in the same session, and modifications made

// within the session will be observed in following queries (read-your-writes).

// http://godoc.org/labix.org/v2/mgo#Session.SetMode

mongoSession.SetMode(mgo.Monotonic, true)

// Create a wait group to manage the goroutines.

var waitGroup sync.WaitGroup

// Perform 10 concurrent queries against the database.

waitGroup.Add(10)

for query := 0; query < 10; query++ {

go RunQuery(query, &waitGroup, mongoSession)

}

// Wait for all the queries to complete.

waitGroup.Wait()

log.Println("All Queries Completed")

}

// RunQuery is a function that is launched as a goroutine to perform

// the MongoDB work.

func RunQuery(query int, waitGroup *sync.WaitGroup, mongoSession *mgo.Session) {

// Decrement the wait group count so the program knows this

// has been completed once the goroutine exits.

defer waitGroup.Done()

// Request a socket connection from the session to process our query.

// Close the session when the goroutine exits and put the connection back

// into the pool.

sessionCopy := mongoSession.Copy()

defer sessionCopy.Close()

// Get a collection to execute the query against.

collection := sessionCopy.DB(TestDatabase).C("buoy_stations")

log.Printf("RunQuery : %d : Executing\n", query)

// Retrieve the list of stations.

var buoyStations []BuoyStation

err := collection.Find(nil).All(&buoyStations)

if err != nil {

log.Printf("RunQuery : ERROR : %s\n", err)

return

}

log.Printf("RunQuery : %d : Count[%d]\n", query, len(buoyStations))

}

文章的脚注信息由WordPress的wp-posturl插件自动生成

|2|left

打赏

1b6439c6a040252321edad911c85491b.png微信扫一扫,打赏作者吧~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Go中实现RabbitMQ的连接池,你可以使用`github.com/streadway/amqp`库结合`sync.Pool`来管理连接对象。这是一个简单的连接池实现示例: ```go import ( "github.com/streadway/amqp" "sync" ) type RabbitMQPool struct { connStr string pool *sync.Pool } func NewRabbitMQPool(connStr string) *RabbitMQPool { return &RabbitMQPool{ connStr: connStr, pool: &sync.Pool{ New: func() interface{} { conn, err := amqp.Dial(connStr) if err != nil { panic(err) // 处理连接错误,这里简单起见直接panic } return conn }, }, } } func (p *RabbitMQPool) GetConnection() *amqp.Connection { return p.pool.Get().(*amqp.Connection) } func (p *RabbitMQPool) ReleaseConnection(conn *amqp.Connection) { p.pool.Put(conn) } ``` 在上面的示例中,`RabbitMQPool`结构体代表了一个RabbitMQ连接池。`NewRabbitMQPool`函数用于创建一个新的连接池对象,传入RabbitMQ的连接字符串作为参数。 `GetConnection`方法用于从连接池中获取一个可用的连接对象。`ReleaseConnection`方法用于将连接对象放回连接池中。 这样,你就可以在你的代码中使用连接池来获取和释放RabbitMQ连接,而无需每次都重新创建和关闭连接。例如: ```go pool := NewRabbitMQPool("amqp://guest:guest@localhost:5672/") // 获取连接 conn := pool.GetConnection() defer pool.ReleaseConnection(conn) // 使用连接进行操作,比如发送消息等 // ... ``` 记得在适当的地方处理连接错误和关闭连接。 请注意,这只是一个简单的示例,你可以根据你的实际需求进行适当的修改和扩展,比如添加连接的最大数量、定时检查连接状态等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值