pubsub

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

📣 Go Pub/Sub 发布订阅模型示例

[!NOTE] This readme is generated by Qwen3.

一个轻量级、并发安全的发布-订阅(Publish-Subscribe)模型示例,使用 Go 语言实现。

✨ 特性

  • 完全并发安全:使用 sync.RWMutex 保护共享状态。
  • 灵活订阅:支持订阅具体主题或所有主题("")。
  • 自动/手动注册:创建实例时可选择是否自动注册到全局管理器。
  • 异步非阻塞发布:发布消息不阻塞,通过 Goroutine 异步投递。
  • 缓冲消息通道:订阅者自带可配置缓冲区的消息通道。
  • 优雅资源管理:提供 Unregister 方法清理资源。
  • 唯一 ID 生成:基于 UUID 生成带类型前缀的唯一 ID。
  • 上下文支持:提供 ConsumeContext 方法支持上下文取消。
  • 完整文档:所有导出类型和方法都有完整的 godoc 注释。

📦 安装

go get github.com/Jinvic/pubsub

🚀 快速开始

package main

import (
    "fmt"
    "time"
    pubsub "github.com/Jinvic/pubsub"
)

func main() {
    // 1. 创建发布者
    publisher := pubsub.NewPublisher(true)

    // 2. 创建订阅者
    subscriber := pubsub.NewSubscriber(10, true)

    // 3. 订阅主题
    subscriber.Subscribe(publisher.ID, "news")
    subscriber.Subscribe(publisher.ID, "") // 订阅所有主题

    // 4. 发布消息
    publisher.Publish([]string{"news"}, []byte("Hello, World!"))

    // 5. 消费消息 (阻塞)
    msg, err := subscriber.Consume()
    if err != nil {
        fmt.Printf("Error consuming message: %v\n", err)
        return
    }
    fmt.Printf("Received: %s\n", string(msg.Data))

    // 或使用非阻塞方式
    if msg, ok, err := subscriber.TryConsume(); ok && err == nil {
        fmt.Printf("Received: %s\n", string(msg.Data))
    } else if err != nil {
        fmt.Printf("Error trying to consume: %v\n", err)
    }

    // 6. 清理资源
    subscriber.Unregister() // 关闭通道并注销订阅者
}

🧰 API 参考

NewPublisher(autoRegister bool) *Publisher

创建新的发布者。

  • autoRegister=true:创建后自动注册到全局 Publishers 映射。
  • 返回:*Publisher
NewSubscriber(bufferSize int, autoRegister bool) *Subscriber

创建新的订阅者。

  • bufferSize<=0:使用默认值 10。
  • autoRegister=true:创建后自动注册。
  • 返回:*Subscriber
Publisher 方法
方法 描述
Publish(topics []string, data []byte) 向指定主题发布消息。
Unregister() 从全局映射中注销该发布者。
Subscriber 方法
方法 描述
Subscribe(pubID, topic string) 订阅某个发布者的主题。
UnsubscribeTopic(pubID, topics []string) 取消订阅指定主题。
UnsubscribePublisher(pubID) 取消订阅该发布者的所有主题。
Receive(msg Message) 接收消息(由发布者调用)。
Consume() (Message, error) 阻塞式消费一条消息,返回消息和错误。
ConsumeContext(ctx context.Context) (Message, error) 带上下文的阻塞消费,支持超时或取消。
TryConsume() (Message, bool, error) 非阻塞消费,返回 (消息, 是否收到, 错误)。
Unregister() 关闭消息通道并注销订阅者。
Message 结构
字段 类型 描述
ID PubSubID 消息唯一标识符
Data []byte 消息内容
Topics []string 消息所属主题列表
Publisher PubSubID 发布者ID
CreatedAt time.Time 消息创建时间
全局函数
函数 描述
RegisterPublisher, RegisterSubscriber 手动注册实例。
UnregisterPublisher, UnregisterSubscriber 手动注销实例。
GetPublisher, GetSubscriber 通过 ID 获取实例。

⚠️ 注意事项

  1. 主题匹配:

    • 订阅 "" 表示接收该发布者的所有消息。
    • 订阅具体主题 "news" 只接收该主题消息。
    • 两者可以同时存在。
  2. 资源清理:

    • 建议在 defer 中调用 subscriber.Unregister() 或 publisher.Unregister()。
    • Unregister() 会关闭 MsgChan,后续 Receive 调用将 panic。
  3. 并发安全:

    • 所有公开方法都是并发安全的。
    • Consume 和 TryConsume 可以在多个 Goroutine 中安全调用。
  4. 错误处理:

    • Consume 和 TryConsume 方法现在返回错误,需要适当处理。
    • 当订阅者关闭时,Consume 和 TryConsume 会返回 ErrSubscriberClosed。
  5. ID 唯一性:基于 github.com/google/uuid 保证全局唯一。


📚 文档

完整的 API 文档可以通过 go doc 查看:

# 在项目目录下运行
go doc

或者 在线查看。


🔍 Todo List

  1. 错误处理:

    • Subscribe/Unsubscribe 方法可以返回 error,例如当发布者不存在时。
    • Publish 可以返回发送成功的订阅者数量。
  2. 消息序列化:

    • 提供 Message 的 JSON 序列化方法,便于日志或网络传输。
  3. 性能监控:

    • 添加计数器统计发布/订阅次数。
  4. 示例目录:

    • 添加 examples/ 目录,提供更复杂的使用场景。

Documentation

Overview

Package pubsub provides a lightweight, concurrent-safe publish-subscribe implementation.

Index

Constants

This section is empty.

Variables

View Source
var ErrSubscriberClosed = errors.New("subscriber closed")

ErrSubscriberClosed is returned when trying to consume from a closed subscriber.

View Source
var Publishers = make(map[PubSubID]*Publisher)

Publishers is a global map of all registered publishers, keyed by their ID.

View Source
var Subscribers = make(map[PubSubID]*Subscriber)

Subscribers is a global map of all registered subscribers, keyed by their ID.

Functions

func RegisterPublisher

func RegisterPublisher(p *Publisher)

RegisterPublisher registers a publisher in the global Publishers map.

func RegisterSubscriber

func RegisterSubscriber(s *Subscriber)

RegisterSubscriber registers a subscriber in the global Subscribers map.

func UnregisterPublisher

func UnregisterPublisher(p *Publisher)

UnregisterPublisher removes a publisher from the global Publishers map.

func UnregisterSubscriber

func UnregisterSubscriber(s *Subscriber)

UnregisterSubscriber removes a subscriber from the global Subscribers map.

Types

type Message

type Message struct {
	// ID is the unique identifier for this message.
	ID PubSubID
	// Data contains the payload of the message.
	Data []byte
	// Topics is a list of topics that this message belongs to.
	Topics []string
	// Publisher is the ID of the publisher that sent this message.
	Publisher PubSubID
	// CreatedAt is the timestamp when the message was created.
	CreatedAt time.Time
}

Message represents a message in the pubsub system.

type PubSubID

type PubSubID string

PubSubID represents a unique identifier for publishers, subscribers, and messages.

type Publisher

type Publisher struct {
	// ID is the unique identifier for this publisher.
	ID PubSubID
	// Subscribers is a map of topic to subscriber IDs.
	Subscribers map[string]map[PubSubID]struct{}
	// contains filtered or unexported fields
}

Publisher represents a publisher in the pubsub system. It maintains a list of subscribers for each topic.

func GetPublisher

func GetPublisher(id PubSubID) *Publisher

GetPublisher retrieves a publisher by its ID from the global Publishers map. Returns nil if the publisher is not found.

func NewPublisher

func NewPublisher(autoRegister bool) *Publisher

NewPublisher creates a new publisher. If autoRegister is true, the publisher is automatically registered in the global Publishers map.

func (*Publisher) AddSubscriber

func (p *Publisher) AddSubscriber(subID PubSubID, topic string)

AddSubscriber adds a subscriber to a specific topic. This method is safe for concurrent use.

func (*Publisher) Publish

func (p *Publisher) Publish(topics []string, data []byte)

Publish sends a message to all subscribers of the specified topics. The message is sent asynchronously using goroutines. If an empty string is a topic, all subscribers (regardless of their specific topic subscriptions) will receive the message.

func (*Publisher) RemoveSubscriber

func (p *Publisher) RemoveSubscriber(subID PubSubID, topics []string)

RemoveSubscriber removes a subscriber from the specified topics. This method is safe for concurrent use.

func (*Publisher) Unregister

func (p *Publisher) Unregister()

Unregister removes this publisher from the global Publishers map.

type Subscriber

type Subscriber struct {
	// ID is the unique identifier for this subscriber.
	ID PubSubID
	// Subscriptions is a map of publisher ID to topic subscriptions.
	Subscriptions map[PubSubID]map[string]struct{}
	// MsgChan is the channel through which messages are received.
	MsgChan chan Message
	// contains filtered or unexported fields
}

Subscriber represents a subscriber in the pubsub system. It maintains subscriptions to publishers and their topics, and provides methods to consume messages.

func GetSubscriber

func GetSubscriber(id PubSubID) *Subscriber

GetSubscriber retrieves a subscriber by its ID from the global Subscribers map. Returns nil if the subscriber is not found.

func NewSubscriber

func NewSubscriber(bufferSize int, autoRegister bool) *Subscriber

NewSubscriber creates a new subscriber. bufferSize specifies the size of the message channel buffer. If bufferSize <= 0, it defaults to 10. If autoRegister is true, the subscriber is automatically registered in the global Subscribers map.

func (*Subscriber) Consume

func (s *Subscriber) Consume() (Message, error)

Consume blocks until a message is received from the message channel. Returns the received message and any error that occurred.

func (*Subscriber) ConsumeContext

func (s *Subscriber) ConsumeContext(ctx context.Context) (Message, error)

ConsumeContext blocks until a message is received or the context is cancelled. Returns the received message and any error that occurred.

func (*Subscriber) Receive

func (s *Subscriber) Receive(msg Message)

Receive receives a message and sends it to the subscriber's message channel. This method is safe for concurrent use.

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(pubID PubSubID, topic string)

Subscribe subscribes to a topic of a specific publisher. This method is safe for concurrent use.

func (*Subscriber) TryConsume

func (s *Subscriber) TryConsume() (Message, bool, error)

TryConsume attempts to receive a message without blocking. Returns the received message, a boolean indicating if a message was received, and any error that occurred.

func (*Subscriber) Unregister

func (s *Subscriber) Unregister()

Unregister closes the message channel and removes the subscriber from the global Subscribers map.

func (*Subscriber) UnsubscribePublisher

func (s *Subscriber) UnsubscribePublisher(pubID PubSubID)

UnsubscribePublisher unsubscribes from all topics of a specific publisher. This method is safe for concurrent use.

func (*Subscriber) UnsubscribeTopic

func (s *Subscriber) UnsubscribeTopic(pubID PubSubID, topics []string)

UnsubscribeTopic unsubscribes from specific topics of a publisher. This method is safe for concurrent use.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL