go-zero/example/http/breaker/server.go

60 lines
1.2 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package main
import (
"net/http"
"runtime"
"time"
2020-08-08 16:40:10 +08:00
"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/core/syncx"
"github.com/tal-tech/go-zero/rest"
2020-07-26 17:09:05 +08:00
)
func main() {
logx.Disable()
stat.SetReporter(nil)
2020-07-31 11:45:16 +08:00
server := rest.MustNewServer(rest.RestConf{
2020-07-26 17:09:05 +08:00
ServiceConf: service.ServiceConf{
Name: "breaker",
Log: logx.LogConf{
Mode: "console",
},
},
Host: "0.0.0.0",
Port: 8080,
MaxConns: 1000,
Timeout: 3000,
})
latch := syncx.NewLimit(10)
2020-07-31 11:14:48 +08:00
server.AddRoute(rest.Route{
2020-07-26 17:09:05 +08:00
Method: http.MethodGet,
Path: "/heavy",
Handler: func(w http.ResponseWriter, r *http.Request) {
if latch.TryBorrow() {
defer latch.Return()
runtime.LockOSThread()
defer runtime.UnlockOSThread()
begin := time.Now()
for {
if time.Now().Sub(begin) > time.Millisecond*50 {
break
}
}
} else {
w.WriteHeader(http.StatusInternalServerError)
}
},
})
2020-07-31 11:14:48 +08:00
server.AddRoute(rest.Route{
2020-07-26 17:09:05 +08:00
Method: http.MethodGet,
Path: "/good",
Handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
})
defer server.Stop()
server.Start()
}