Class MessageBus

java.lang.Object
dev.ua.theroer.magicutils.messaging.MessageBus
All Implemented Interfaces:
AutoCloseable

public final class MessageBus extends Object implements AutoCloseable
Typed cross-server publish/subscribe bus for MagicUtils plugins.

Wraps a pluggable MessageTransport (the default per-platform plugin-messaging transport, or Redis) with a channel-oriented, typed API: subscribe(String, Class, MessageHandler) and publish(Target, String, Object). Payloads are serialized with a shared MessageCodec. The bus applies Target addressing on receipt so routing behaves identically regardless of which transport is in use.

The bus is AutoCloseable and is meant to be registered with a MagicRuntime so it is torn down with the plugin.

  • Method Details

    • builder

      public static MessageBus.Builder builder(MessageSource self, MessageTransport transport)
      Creates a bus builder.
      Parameters:
      self - this member's identity
      transport - underlying transport
      Returns:
      builder
    • self

      public MessageSource self()
      Returns this member's identity.
      Returns:
      self source
    • transport

      public MessageTransport transport()
      Returns the underlying transport.
      Returns:
      transport
    • codec

      public MessageCodec codec()
      Returns the codec used for payload serialization.
      Returns:
      message codec
    • hostsPlayer

      public void hostsPlayer(@Nullable @Nullable Predicate<UUID> hostsPlayer)
      Sets the predicate answering whether this member hosts a given player id.

      Used to honour Target.player(UUID) on backends. Ignored on the proxy. May be updated at any time (for example wired to the online-player registry).

      Parameters:
      hostsPlayer - predicate, or null to disable player-target delivery
    • publish

      public void publish(Target target, String channel, @Nullable @Nullable Object payload)
      Publishes a payload on a channel to the given target.
      Parameters:
      target - addressing hint
      channel - logical channel name
      payload - payload object (serialized with the shared codec; may be null)
    • broadcast

      public void broadcast(String channel, @Nullable @Nullable Object payload)
      Broadcasts a payload on a channel to every subscriber on the network.
      Parameters:
      channel - logical channel name
      payload - payload object
    • subscribe

      public <T> ListenerSubscription subscribe(String channel, Class<T> type, MessageHandler<T> handler)
      Subscribes a typed handler to a channel.
      Type Parameters:
      T - payload type
      Parameters:
      channel - logical channel name
      type - payload type
      handler - message handler
      Returns:
      subscription handle; close it to unsubscribe
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable