序
本文次要钻研一下 go.cqrs 的 Dispatcher
Dispatcher
type Dispatcher interface {Dispatch(CommandMessage) error
RegisterHandler(CommandHandler, ...interface{}) error
}
Dispatcher 接口定义了 Dispatch、RegisterHandler 办法
InMemoryDispatcher
type InMemoryDispatcher struct {handlers map[string]CommandHandler
}
//NewInMemoryDispatcher constructs a new in memory dispatcher
func NewInMemoryDispatcher() *InMemoryDispatcher {
b := &InMemoryDispatcher{handlers: make(map[string]CommandHandler),
}
return b
}
//Dispatch passes the CommandMessage on to all registered command handlers.
func (b *InMemoryDispatcher) Dispatch(command CommandMessage) error {if handler, ok := b.handlers[command.CommandType()]; ok {return handler.Handle(command)
}
return fmt.Errorf("The command bus does not have a handler for commands of type: %s", command.CommandType())
}
//RegisterHandler registers a command handler for the command types specified by the
//variadic commands parameter.
func (b *InMemoryDispatcher) RegisterHandler(handler CommandHandler, commands ...interface{}) error {
for _, command := range commands {typeName := typeOf(command)
if _, ok := b.handlers[typeName]; ok {return fmt.Errorf("Duplicate command handler registration with command bus for command of type: %s", typeName)
}
b.handlers[typeName] = handler
}
return nil
}
InMemoryDispatcher 定义了 map[string]CommandHandler 属性,其 Dispatch 办法依据 command.CommandType() 获取 handler,而后执行 handler.Handle(command);其 RegisterHandler 办法遍历 commands,而后获取 command 的 type,挨个注册到 map[string]CommandHandler 中
CommandHandler
// CommandHandler is the interface that all command handlers should implement.
type CommandHandler interface {Handle(CommandMessage) error
}
// CommandMessage is the interface that a command message must implement.
type CommandMessage interface {
// AggregateID returns the ID of the Aggregate that the command relates to
AggregateID() string
// Headers returns the key value collection of headers for the command.
Headers() map[string]interface{}
// SetHeader sets the value of the header specified by the key
SetHeader(string, interface{})
// Command returns the actual command which is the payload of the command message.
Command() interface{}
// CommandType returns a string descriptor of the command name
CommandType() string}
CommandHandler 接口定义了 Handle 办法;CommandMessage 接口定义了 AggregateID、Headers、SetHeader、Command、CommandType 办法
小结
go.cqrs 的 Dispatcher 接口定义了 Dispatch、RegisterHandler 办法;InMemoryDispatcher 定义了 map[string]CommandHandler 属性,其 Dispatch 办法依据 command.CommandType() 获取 handler,而后执行 handler.Handle(command);其 RegisterHandler 办法遍历 commands,而后获取 command 的 type,挨个注册到 map[string]CommandHandler 中。
doc
- go.cqrs