前言
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 }
方法
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{}
结构名称要大写,否则编译不过去。
下一章
下一章继续关于组件的讨论,组件会变成服务,而服务提供具体方法
今天的文章 go开源网络库nano(8)-组件分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/92357.html