/
std_service.go
135 lines (113 loc) · 2.47 KB
/
std_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// Copyright 2021 XinRui Hua. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package engine
import (
"net"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/huaxr/rx/ctx"
"github.com/huaxr/rx/logger"
)
type TYPE string
const (
HTTP TYPE = "http"
TCP TYPE = "tcp"
)
// TcpSocket the raw socket
type stdServer struct {
//reader io.Reader
listener net.Listener
ch []chan net.Conn
tickQps *time.Ticker
tickHb *time.Ticker
count int
qps int
goroutine int
typ TYPE
}
const qpsPeriod = 1
const hbPeriod = 10
const LB = 1 << 6
func (t *stdServer) GetAddr() string {
return t.listener.Addr().String()
}
func NewStdServer(addr string) *stdServer {
t := new(stdServer)
once := sync.Once{}
once.Do(func() {
listen, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
}
t.listener = listen
ch := make(chan net.Conn, 500)
for i := 1; i <= LB; i++ {
t.ch = append(t.ch, ch)
}
t.tickQps = time.NewTicker(qpsPeriod * time.Second)
t.tickHb = time.NewTicker(hbPeriod * time.Second)
go t.heartBeat()
t.do()
})
return t
}
func (t *stdServer) heartBeat() {
for {
select {
case <-t.tickQps.C:
//last_qps := t.qps
t.qps = t.count / qpsPeriod
if t.qps > 0 {
logger.Log.Info("current qps: %d/s", t.qps)
}
t.count = 0
case <-t.tickHb.C:
g_num := runtime.NumGoroutine()
t.goroutine = g_num
// export GODEBUG='gctrace=1'
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
logger.Log.Info("current goroutine count: %d; MemStates: Alloc:%d(MB) HeapIdle:%d(MB) HeapInuse:%d(MB)", g_num, ms.Alloc/(1024*1024), ms.HeapIdle/(1024*1024), ms.HeapInuse/(1024*1024))
// force gc.
//runtime.GC()
debug.FreeOSMemory()
}
}
}
func (t *stdServer) Run() {
ctx.Print()
logger.Log.Info("start server on: %v", t.GetAddr())
for {
rawConn, err := t.listener.Accept()
if err != nil {
logger.Log.Error("Err listening, %v", err.Error())
continue
}
ip := rawConn.RemoteAddr().String()
ip = strings.ReplaceAll(ip[len(ip)-9:], ".", "")
ip = strings.ReplaceAll(ip, ":", "")
lb, _ := strconv.Atoi(ip)
// multiple channel can enhance the performance
t.ch[lb%LB] <- rawConn
}
}
func (t *stdServer) Type(typ TYPE) {
t.typ = typ
}
func (t *stdServer) do() {
for _, channel := range t.ch {
channel := channel
go func() {
for {
c := <-channel
ctx.WrapStd(c, string(t.typ))
t.count++
}
}()
}
}