在结构体(析构函数)变量上设置defer的位置在哪里?

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年12月3日 19:27:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/34064825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定