forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
71 lines (63 loc) · 1.25 KB
/
server.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
package main
import (
"fmt"
"net/http"
"runtime"
"time"
"github.com/tal-tech/go-zero/core/fx"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/service"
"github.com/tal-tech/go-zero/core/stat"
"github.com/tal-tech/go-zero/rest"
)
const duration = time.Millisecond
func main() {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
fmt.Printf("cpu: %d\n", stat.CpuUsage())
}
}()
logx.Disable()
engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{
Log: logx.LogConf{
Mode: "console",
},
},
Host: "0.0.0.0",
Port: 3333,
CpuThreshold: 800,
})
defer engine.Stop()
engine.AddRoute(rest.Route{
Method: http.MethodGet,
Path: "/",
Handler: func(w http.ResponseWriter, r *http.Request) {
if err := fx.DoWithTimeout(func() error {
job(duration)
return nil
}, time.Millisecond*100); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
}
},
})
engine.Start()
}
func job(duration time.Duration) {
done := make(chan int)
for i := 0; i < runtime.NumCPU(); i++ {
go func() {
for {
select {
case <-done:
return
default:
}
}
}()
}
time.Sleep(duration)
close(done)
}