前言
package component
组件
定义
//Component 组件的接口
type Component interface {
Init()
AfterInit()
BeforeShutdown()
Shutdown()
}
// base 是基本的,默认的实现
type Base struct{}
// Init was called to initialize the component.
func (c *Base) Init() {}
// AfterInit was called after the component is initialized.
func (c *Base) AfterInit() {}
// BeforeShutdown was called before the component to shutdown.
func (c *Base) BeforeShutdown() {}
// Shutdown was called to shutdown the component.
func (c *Base) Shutdown() {}
//Option
options struct {
name string // component name
nameFunc func(string) string // rename handler name
schedName string // schedName name
}
// Option used to customize handler 对options结构体进行设置的函数模板
Option func(options *options)
type CompWithOptions struct {
Comp Component
Opts []Option //对options进行设置的函数组
}
type Components struct {
comps []CompWithOptions
}
Components 是总组件,可以接受多个组件的注册。 每个组件又可以提供不同的逻辑处理。
Component 是接口,base是实现接口的一个简单的结构,默认初始化用。
方法
1. 注册
// Register registers a component to hub with options
func (cs *Components) Register(c Component, options ...Option) {
cs.comps = append(cs.comps, CompWithOptions{c, options})
}
2.获取组件列表
// List returns all components with it's options
func (cs *Components) List() []CompWithOptions {
return cs.comps
}
举个例子demo
//demo.go
package demo
import (
"github.com/lonng/nano/component"
"github.com/lonng/nano/session"
"log"
)
type Demo struct {
component.Base
sq int64
}
func newDemo() *Demo {
return &Demo{}
}
func (ds *Demo) Dprint(s *session.Session, msg []byte) error {
log.Println("hello,Demo!")
return nil
}
//demo_init.go
package demo
var (
// All services in master server
Services = &component.Components{}
demoService = newdemoService()
)
func init() {
Services.Register(demoService )
}
// main.go
package main
import (
"github.com/lonng/nano"
"github.com/lonng/nano/examples/myDemo/demo"
)
func main() {
listen := "127.0.0.1:10000"
nano.Listen(listen,
nano.WithMaster(),
nano.WithComponents(demo.Services),
nano.WithDebugMode(),
)
}
执行后的结构:
在编译的时候出现个问题:
type Demo struct{}
结构名称要大写,否则编译不过去。
下一章
下一章继续关于组件的讨论,组件会变成服务,而服务提供具体方法