conn_num.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package limiter
  2. import (
  3. "ehang.io/nps/lib/enet"
  4. "errors"
  5. "sync/atomic"
  6. )
  7. // ConnNumLimiter is used to limit the connection num of a service
  8. type ConnNumLimiter struct {
  9. baseLimiter
  10. nowNum int32
  11. MaxConnNum int32 `json:"max_conn_num" required:"true" placeholder:"10" zh_name:"最大连接数"` //0 means not limit
  12. }
  13. func (cl *ConnNumLimiter) GetName() string {
  14. return "conn_num"
  15. }
  16. func (cl *ConnNumLimiter) GetZhName() string {
  17. return "总连接数限制"
  18. }
  19. // DoLimit return an error if the connection num exceed the maximum
  20. func (cl *ConnNumLimiter) DoLimit(c enet.Conn) (enet.Conn, error) {
  21. if atomic.AddInt32(&cl.nowNum, 1) > cl.MaxConnNum && cl.MaxConnNum > 0 {
  22. atomic.AddInt32(&cl.nowNum, -1)
  23. return nil, errors.New("exceed maximum number of connections")
  24. }
  25. return &connNumConn{nowNum: &cl.nowNum}, nil
  26. }
  27. // connNumConn is an implementation of enet.Conn
  28. type connNumConn struct {
  29. nowNum *int32
  30. enet.Conn
  31. }
  32. // Close decrease the connection num
  33. func (cn *connNumConn) Close() error {
  34. atomic.AddInt32(cn.nowNum, -1)
  35. return cn.Conn.Close()
  36. }