英文:
Where to set defer on a struct(destructor) variable
问题
我有一个包含数据库会话变量的结构体。我应该在哪里设置/调用defer - 类似于构造函数/析构函数?
type MyType struct {
session *gocql.Session
}
我附加了一个*gocql.Session
的实例,它应该与结构体一样长久存在。
func (this *myType) function_one_using_the_session(){}
func (this *myType) function_two_using_the_session(){}
我找到了这个:runtime.SetFinalizer(a, func(a *Test) { fmt.Println("I AM DEAD") })
。
我可能会这样做,或者编写自己的Close()
函数。
这可能会起作用,还有其他的意见吗?
我试图只使用有限数量的会话。但是在下面的函数中,我应该延迟关闭会话吗?
func GetSession() *gocql.Session {
if cluster == nil {
cluster = gocql.NewCluster("ip")
cluster.Keyspace = "Keyspace"
session, _ = cluster.CreateSession()
return session
} else {
session, _ = cluster.CreateSession()
// defer session.Close()
}
return session
}
英文:
I have a struct with a database session variable. Where should I set/call defer on this - like a constructor/destructor?
type MyType struct {
session *gocql.Session
}
I am attaching an instance of *gocql.Session and it should live as long as the struct.
func (this *myType) function_one_using_the_session(){}
func (this *myType) function_two_using_the_session(){}
I found this: runtime.SetFinalizer(a, func(a *Test) { fmt.Println("I AM DEAD") })
I will probably do that or write my own Close()
function.
This might do the trick - other comments is welcome?
I am trying to use only so many sessions. But should I defer the session in the following function:
func GetSession() *gocql.Session {
if cluster == nil {
cluster = gocql.NewCluster("ip")
cluster.Keyspace = "Keyspace"
session, _ = cluster.CreateSession()
return session
} else {
session, _ = cluster.CreateSession()
// defer session.Close()
}
return session
}
答案1
得分: 1
你可以使用上下文来设置Cassandra会话,并在使用后释放它,将其返回到会话池中。请参考这篇博文,了解如何组织对数据库服务的访问:链接。
英文:
You may compose your handlers using a context for setting the Cassandra session, use it and release afterwards, returning it to your pool of sessions.
Take a look to this blog post about about how to organize your access to DB services.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论