micro.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package micro
  2. import (
  3. "context"
  4. "git.nspix.com/golang/micro/gateway/cli"
  5. "github.com/google/btree"
  6. "time"
  7. "git.nspix.com/golang/micro/gateway/http"
  8. "git.nspix.com/golang/micro/gateway/rpc"
  9. "git.nspix.com/golang/micro/registry"
  10. )
  11. const (
  12. EnvironmentDocker string = "docker"
  13. EnvironmentHost = "host"
  14. )
  15. type (
  16. applicationKey struct {
  17. }
  18. handleEntry struct {
  19. Method string `json:"method"`
  20. Func HandleFunc
  21. Options []HandleOption
  22. }
  23. HandleTickerFunc func(ctx context.Context)
  24. tickPtr struct {
  25. sequence int64
  26. next time.Time
  27. running int32
  28. options *TickOptions
  29. callback HandleTickerFunc
  30. }
  31. TickOptions struct {
  32. Context context.Context
  33. Canceled bool
  34. MustBeExecute bool
  35. }
  36. TickOption func(o *TickOptions)
  37. HandleOptions struct {
  38. DisableRpc bool //禁用RPC功能
  39. DisableHttp bool //禁用HTTP功能
  40. DisableCli bool //禁用CLI功能
  41. HttpPath string //重定向HTTP路由
  42. HttpMethod string //HTTP路径
  43. }
  44. HandleOption func(o *HandleOptions)
  45. HandleFunc func(ctx Context) (err error)
  46. Application interface {
  47. Node() *registry.ServiceNode //获取节点信息
  48. HttpServe() *http.Server //获取HTTP实例
  49. RPCServe() *rpc.Server //获取RPC实例
  50. CliServe() *cli.Server //获取cli服务端
  51. PeekService(name string) ([]*registry.ServiceNode, error) //选择一个服务
  52. Handle(method string, cb HandleFunc, opts ...HandleOption) //注册一个处理器
  53. NewRequest(name, method string, body interface{}) (req *Request, err error) //创建一个rpc请求
  54. DeferTick(duration time.Duration, callback HandleTickerFunc, opts ...TickOption) int64 //异步任务
  55. Environment() string
  56. }
  57. Server interface {
  58. Start(ctx context.Context) (err error)
  59. Stop() (err error)
  60. }
  61. )
  62. var (
  63. contextKey = applicationKey{}
  64. )
  65. func (p tickPtr) Less(i btree.Item) bool {
  66. q := i.(*tickPtr)
  67. if p.next.Before(q.next) {
  68. return true
  69. } else if p.sequence < q.sequence {
  70. return true
  71. }
  72. return false
  73. }
  74. func FromContext(ctx context.Context) Application {
  75. if v := ctx.Value(contextKey); v != nil {
  76. return v.(Application)
  77. }
  78. return nil
  79. }
  80. func WithContext(ctx context.Context, app Application) context.Context {
  81. return context.WithValue(ctx, contextKey, app)
  82. }