micro.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. HandleTickerFunc func(ctx context.Context)
  19. tickPtr struct {
  20. sequence int64
  21. next time.Time
  22. running int32
  23. options *TickOptions
  24. callback HandleTickerFunc
  25. }
  26. TickOptions struct {
  27. Context context.Context
  28. Canceled bool
  29. MustBeExecute bool
  30. }
  31. TickOption func(o *TickOptions)
  32. HandleOptions struct {
  33. DisableRpc bool //禁用RPC功能
  34. DisableHttp bool //禁用HTTP功能
  35. DisableCli bool //禁用CLI功能
  36. HttpPath string //重定向HTTP路由
  37. HttpMethod string //HTTP路径
  38. }
  39. HandleOption func(o *HandleOptions)
  40. HandleFunc func(ctx Context) (err error)
  41. Application interface {
  42. Node() *registry.ServiceNode //获取节点信息
  43. HttpServe() *http.Server //获取HTTP实例
  44. RPCServe() *rpc.Server //获取RPC实例
  45. CliServe() *cli.Server //获取cli服务端
  46. PeekService(name string) ([]*registry.ServiceNode, error) //选择一个服务
  47. Handle(method string, cb HandleFunc, opts ...HandleOption) //注册一个处理器
  48. NewRequest(name, method string, body interface{}) (req *Request, err error) //创建一个rpc请求
  49. DeferTick(duration time.Duration, callback HandleTickerFunc, opts ...TickOption) int64 //异步任务
  50. Environment() string
  51. }
  52. Server interface {
  53. Start(ctx context.Context) (err error)
  54. Stop() (err error)
  55. }
  56. )
  57. var (
  58. contextKey = applicationKey{}
  59. )
  60. func (p tickPtr) Less(i btree.Item) bool {
  61. q := i.(*tickPtr)
  62. if p.next.Before(q.next) {
  63. return true
  64. } else if p.sequence < q.sequence {
  65. return true
  66. }
  67. return false
  68. }
  69. func FromContext(ctx context.Context) Application {
  70. if v := ctx.Value(contextKey); v != nil {
  71. return v.(Application)
  72. }
  73. return nil
  74. }
  75. func WithContext(ctx context.Context, app Application) context.Context {
  76. return context.WithValue(ctx, contextKey, app)
  77. }