micro.go 2.4 KB

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