gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/util/socket/pool.go (about)

     1  package socket
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  type Pool struct {
     8  	sync.RWMutex
     9  	pool map[string]*Socket
    10  }
    11  
    12  func (p *Pool) Get(id string) (*Socket, bool) {
    13  	// attempt to get existing socket
    14  	p.RLock()
    15  	socket, ok := p.pool[id]
    16  	if ok {
    17  		p.RUnlock()
    18  		return socket, ok
    19  	}
    20  	p.RUnlock()
    21  
    22  	// create new socket
    23  	socket = New(id)
    24  	// save socket
    25  	p.Lock()
    26  	p.pool[id] = socket
    27  	p.Unlock()
    28  	// return socket
    29  	return socket, false
    30  }
    31  
    32  func (p *Pool) Release(s *Socket) {
    33  	p.Lock()
    34  	defer p.Unlock()
    35  
    36  	// close the socket
    37  	s.Close()
    38  	delete(p.pool, s.id)
    39  }
    40  
    41  // Close the pool and delete all the sockets
    42  func (p *Pool) Close() {
    43  	p.Lock()
    44  	defer p.Unlock()
    45  	for id, sock := range p.pool {
    46  		sock.Close()
    47  		delete(p.pool, id)
    48  	}
    49  }
    50  
    51  // NewPool returns a new socket pool
    52  func NewPool() *Pool {
    53  	return &Pool{
    54  		pool: make(map[string]*Socket),
    55  	}
    56  }