Basic Pub/Sub
Publish and subscribe to real-time KubeMQ events with the Ruby SDK for fire-and-forget pub/sub messaging across clients.
Overview
This tutorial builds the "hello world" of KubeMQ messaging: a publisher and a subscriber talking over the Events pattern. Events are fire-and-forget — the broker fans a message out to every subscriber currently listening on the channel and moves on. There's no persistence, no acknowledgment, and no replay, which makes this the pattern to reach for when you need low-latency, high-throughput broadcast (metrics ticks, live status updates, cache-invalidation signals) and can tolerate losing a message if nobody is listening at the moment it's sent.
You'll wire up subscribe_to_events with an EventsSubscription and a block, give the subscription a moment to register with the server, then call send_event to publish an EventMessage. Every connected subscriber on the channel gets its own copy, as opposed to a consumer group where only one member would receive it. Gotchas: if the subscriber isn't fully established before you publish, the event is simply gone — there's no queue catching it, which is why the sample sleeps briefly before sending; and because delivery isn't acknowledged, a crashed or disconnected subscriber never knows it missed anything.
Prerequisites
- KubeMQ server running on
localhost:50000 - Ruby SDK installed (
gem install kubemq)
Code
require 'kubemq'
address = ENV.fetch('KUBEMQ_ADDRESS', 'localhost:50000')
channel = 'ruby-events.basic-pubsub'
begin
client = KubeMQ::PubSubClient.new(address: address, client_id: 'pubsub-example')
puts "Connected to #{address}"
cancel = KubeMQ::CancellationToken.new
sub = KubeMQ::PubSub::EventsSubscription.new(channel: channel)
client.subscribe_to_events(sub, cancellation_token: cancel, on_error: ->(e) { puts "Error: #{e.message}" }) do |event|
puts "Received: channel=#{event.channel}, metadata=#{event.metadata}, body=#{event.body}"
end
sleep 1
3.times do |i|
msg = KubeMQ::PubSub::EventMessage.new(
channel: channel,
metadata: "event #{i}",
body: "payload-#{i}"
)
client.send_event(msg)
puts "Sent event #{i}"
end
sleep 2
rescue KubeMQ::Error => e
puts "KubeMQ error: #{e.message}"
ensure
cancel&.cancel
client&.close
puts 'Done'
endHow It Works
subscribe_to_eventstakes a block — idiomatic Ruby for callback-based subscriptions.CancellationTokenprovides cooperative cancellation for the background subscription thread.- Events are fire-and-forget — the broker does not guarantee persistence.
- Review timeouts, channel names, and client IDs before running against shared environments.
Related
Was this page helpful?