代码之家  ›  专栏  ›  技术社区  ›  ceth

如果资源是结构的成员,则何时以及如何关闭它们

go
  •  2
  • ceth  · 技术社区  · 7 年前

    下面是使用defer的经典示例:

    conn, err = amqp.Dial(rabbitMqConnectionString)
    if err != nil {
        panic(err)
    }
    defer conn.Close()
    

    在我的例子中,连接是struct的成员,我在不同的函数中使用这个连接:

    type MyServer {
      conn *Connection
    }
    
    func (s *MyServer) Run() {
      s.conn, err = amqp.Dial(rabbitMqConnectionString)
      if err != nil {
        panic(err)
      }
    }
    
    func (s *MyServer) DoSomethingWithConnection() {
      // ...do something with connection
    }
    

    在这种情况下,我不能在 Run() 方法。但在这种情况下,我需要在哪里以及如何关闭连接?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Uvelichitel    7 年前
    func (s *MyServer) Stop() {
        //Some teardown
       s.conn.Close()
    }
    func main(){
        var s *MyServer
        ...
        s.Run()
        defer s.Stop()
        s.DoSomethingWithConnection()
    }
    
        2
  •  1
  •   VonC    7 年前

    如你所见我 streadway/amqp/integration_test.go 使用连接的函数负责关闭:

    if c := integrationConnection(t, "txcommit"); c != nil {
        defer c.Close()
        ...
    }
    

    使用:

    // Returns a connection to the AMQP if the AMQP_URL environment
    // variable is set and a connection can be established.
    func integrationConnection(t *testing.T, name string) *Connection {
        conn, err := Dial(integrationURLFromEnv())
        if err != nil {
            t.Errorf("dial integration server: %s", err)
            return nil
        }
        return loggedConnection(t, conn, name)
    }
    

    以及:

    func loggedConnection(t *testing.T, conn *Connection, name string) *Connection {
        if name != "" {
            conn.conn = &logIO{t, name, conn.conn}
        }
        return conn
    }