go开源网络库nano(8)-组件

前言

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{}
结构名称要大写,否则编译不过去。

下一章

下一章继续关于组件的讨论,组件会变成服务,而服务提供具体方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值