英文:
mongodb insert from my function using shared session variables
问题
嗨,我已经成功翻译了你的内容,以下是翻译结果:
嗨,我成功地使以下文档插入工作,并且可以调用该函数。然而,我怀疑该函数中的数据库连接部分效率不高,因为我每分钟调用它30-40次。
我需要将数据库会话连接移到函数外部,我认为与*mongoSession有关,但无法使其正常工作。希望能得到帮助。
简而言之:如何将连接移到函数外部
func insertmgo(aaa string, bbb string, ccc time.Time, wg *sync.WaitGroup) {
// mongo stuff
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: AuthPassword,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
mongoSession.SetMode(mgo.Monotonic, true)
c := mongoSession.DB("x").C("ships")
oneship.Created = ccc
oneship.Name = bbb
oneship.Type = aaa
c.Insert(oneship)
wg.Done()
}
希望对你有所帮助!
英文:
Hi i got the following document insert to work properly and i can call the function. However, i doubt that the DB connect stuff in this function is very efficient since i call it 30-40 times per minute.
i need to move the db session connect outside my function and i think its something with *mongoSession, but cant get it to work. Any help would be appriciated.
tldr: How do i move the connection outside the function
func insertmgo(aaa string, bbb string, ccc time.Time, wg *sync.WaitGroup) {
// mongo stuff
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: AuthPassword,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
mongoSession.SetMode(mgo.Monotonic, true)
c := mongoSession.DB("x").C("ships")
oneship.Created = ccc
oneship.Name = bbb
oneship.Type = aaa
c.Insert(oneship)
wg.Done()
}
答案1
得分: 1
找到解决方案
主函数 {
MongoDB操作
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: AuthPassword,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
}
使用以下方式调用函数
fun(mongoSession, .....)
在你的函数中
func fun(db *mgo.Session, .... , wg *sync.WaitGroup) {
我认为就是这样了。不确定是否还有其他或更好的方法,但这对我来说似乎有效。
英文:
found soloution
main {
mongo stuff
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: AuthPassword,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
}
call function with
fun(mongoSession, .....)
in your function
func fun(db *mgo.Session, .... , wg *sync.WaitGroup) {
that was is i think. not sure if there is other or better ways to do it, but this seem to work for me.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论