server.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "time"
  7. "github.com/tal-tech/go-zero/core/fx"
  8. "github.com/tal-tech/go-zero/core/logx"
  9. "github.com/tal-tech/go-zero/core/service"
  10. "github.com/tal-tech/go-zero/core/stat"
  11. "github.com/tal-tech/go-zero/rest"
  12. )
  13. const duration = time.Millisecond
  14. func main() {
  15. go func() {
  16. ticker := time.NewTicker(time.Second)
  17. defer ticker.Stop()
  18. for range ticker.C {
  19. fmt.Printf("cpu: %d\n", stat.CpuUsage())
  20. }
  21. }()
  22. logx.Disable()
  23. engine := rest.MustNewServer(rest.RestConf{
  24. ServiceConf: service.ServiceConf{
  25. Log: logx.LogConf{
  26. Mode: "console",
  27. },
  28. },
  29. Host: "0.0.0.0",
  30. Port: 3333,
  31. CpuThreshold: 800,
  32. })
  33. defer engine.Stop()
  34. engine.AddRoute(rest.Route{
  35. Method: http.MethodGet,
  36. Path: "/",
  37. Handler: func(w http.ResponseWriter, r *http.Request) {
  38. if err := fx.DoWithTimeout(func() error {
  39. job(duration)
  40. return nil
  41. }, time.Millisecond*100); err != nil {
  42. w.WriteHeader(http.StatusServiceUnavailable)
  43. }
  44. },
  45. })
  46. engine.Start()
  47. }
  48. func job(duration time.Duration) {
  49. done := make(chan int)
  50. for i := 0; i < runtime.NumCPU(); i++ {
  51. go func() {
  52. for {
  53. select {
  54. case <-done:
  55. return
  56. default:
  57. }
  58. }
  59. }()
  60. }
  61. time.Sleep(duration)
  62. close(done)
  63. }