github.com/cnotch/ipchub@v1.1.0/stats/conns.go (about) 1 // Copyright (c) 2019,CAOHONGJU All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE file. 4 5 package stats 6 7 import ( 8 "sync/atomic" 9 ) 10 11 // 全局变量 12 var ( 13 RtspConns = NewConns() // RTSP连接统计 14 FlvConns = NewConns() // flv连接统计 15 ) 16 17 // ConnsSample 连接计数采样 18 type ConnsSample struct { 19 Total int64 `json:"total"` 20 Active int64 `json:"active"` 21 } 22 23 // Conns 连接统计 24 type Conns interface { 25 Add() int64 26 Release() int64 27 GetSample() ConnsSample 28 } 29 30 func (s *ConnsSample) clone() ConnsSample { 31 return ConnsSample{ 32 Total: atomic.LoadInt64(&s.Total), 33 Active: atomic.LoadInt64(&s.Active), 34 } 35 } 36 37 type conns struct { 38 sample ConnsSample 39 } 40 41 // NewConns 新建连接计数 42 func NewConns() Conns { 43 return &conns{} 44 } 45 46 func (c *conns) Add() int64 { 47 atomic.AddInt64(&c.sample.Total, 1) 48 return atomic.AddInt64(&c.sample.Active, 1) 49 } 50 51 func (c *conns) Release() int64 { 52 return atomic.AddInt64(&c.sample.Active, -1) 53 } 54 55 func (c *conns) GetSample() ConnsSample { 56 return c.sample.clone() 57 }