feat: 重构事件处理,添加默认通道和发布逻辑,移除不必要的提供者

This commit is contained in:
Rogee
2025-09-11 14:51:40 +08:00
parent ced4202dc9
commit c0d8f070e4
14 changed files with 266 additions and 193 deletions

View File

@@ -14,7 +14,7 @@ const DefaultPrefix = "Events"
func DefaultProvider() container.ProviderContainer {
return container.ProviderContainer{
Provider: Provide,
Provider: ProvideChannel,
Options: []opt.Option{
opt.Prefix(DefaultPrefix),
},
@@ -22,15 +22,30 @@ func DefaultProvider() container.ProviderContainer {
}
type Config struct {
ConsumerGroup string
Sql *ConfigSql
Kafka *ConfigKafka
Redis *ConfigRedis
}
Brokers []string
type ConfigSql struct {
ConsumerGroup string
}
type ConfigRedis struct {
ConsumerGroup string
Streams []string
}
type ConfigKafka struct {
ConsumerGroup string
Brokers []string
}
type PubSub struct {
Publisher message.Publisher
Subscriber message.Subscriber
Router *message.Router
Router *message.Router
publishers map[contracts.Channel]message.Publisher
subscribers map[contracts.Channel]message.Subscriber
}
func (ps *PubSub) Serve(ctx context.Context) error {
@@ -40,15 +55,6 @@ func (ps *PubSub) Serve(ctx context.Context) error {
return nil
}
func (ps *PubSub) Handle(
handlerName string,
consumerTopic string,
publisherTopic string,
handler message.HandlerFunc,
) {
ps.Router.AddHandler(handlerName, consumerTopic, ps.Subscriber, publisherTopic, ps.Publisher, handler)
}
// publish
func (ps *PubSub) Publish(e contracts.EventPublisher) error {
if e == nil {
@@ -61,5 +67,33 @@ func (ps *PubSub) Publish(e contracts.EventPublisher) error {
}
msg := message.NewMessage(watermill.NewUUID(), payload)
return ps.Publisher.Publish(e.Topic(), msg)
return ps.getPublisher(e.Channel()).Publish(e.Topic(), msg)
}
// getPublisher returns the publisher for the specified channel.
func (ps *PubSub) getPublisher(channel contracts.Channel) message.Publisher {
if pub, ok := ps.publishers[channel]; ok {
return pub
}
return ps.publishers[Go]
}
func (ps *PubSub) getSubscriber(channel contracts.Channel) message.Subscriber {
if sub, ok := ps.subscribers[channel]; ok {
return sub
}
return ps.subscribers[Go]
}
func (ps *PubSub) Handle(handlerName string, sub contracts.EventHandler) {
publishToCh, publishToTopic := sub.PublishTo()
ps.Router.AddHandler(
handlerName,
sub.Topic(),
ps.getSubscriber(sub.Channel()),
publishToTopic,
ps.getPublisher(publishToCh),
sub.Handler,
)
}