Publish/Subscribe Events

../../_images/example-pubsub-events.png

Publish/Subscribe Events

Introduction

This example will show you how to use publish/subscribe events in your services.

Internally, Baratine uses pub/sub events for server start and stop notification.

Prerequisites

See the Hello World example for setting up a workspace and building a Baratine project.

event: scheme

The built-in event: Service scheme is a publish-subscribe broker for API-based events.

Source Code

Event API (MyEvents.java)

public interface MyEvents
{
  void onMessage(String message);
}

Publisher (MyPub.java)

MyPub.java:

@Service("public:///publisher")
public class MyPub implements PubService
{
  private MyEvents _events;

  @OnInit
  public void onInit()
  {
    ServiceManager manager = ServiceManager.current();

    _events = manager.lookup("event:///" + MyEvents.class.getName())
                     .as(MyEvents.class);
  }

  public void message(String message)
  {
    _events.onMessage(message);
  }
}

PubService.java:

public interface PubService
{
  void message(String message);
}

Subscriber (MySub.java)

MySub.java:

import io.baratine.core.Service;
import io.baratine.core.Startup;
import io.baratine.core.OnInit;

@Service("public:///subscriber")
@Startup
public class MySub implements SubService
{
  private int _messageCount;
  private String _lastMessage;

  @OnInit
  private void onInit()
  {
    ServiceManager manager = ServiceManager.current();

    ServiceRef eventRef;

    eventRef = manager.lookup("event:///" + MyEvents.class.getName());

    eventRef.subscribe(msg->onMessage(msg));
  }

  private void onMessage(String msg)
  {
    _lastMessage = msg;
    _messageCount++;
  }

  public String get()
  {
    return ("message-count: " + _messageCount
            + " last-message: " + _lastMessage);
  }
}

MySubService.java:

public interface MySubService
{
  String get();
}