Class ServiceBroker

All Implemented Interfaces:
MetricConstants

public class ServiceBroker extends ContextSource implements MetricConstants
The ServiceBroker is the main component of Moleculer. It handles services & events, calls actions and communicates with remote nodes. You need to create an instance of ServiceBroker for every node. Features of Moleculer:
  • Fast - High-performance and non-blocking
  • Polyglot - Moleculer is implemented under Node.js and Java
  • Extensible - All built-in modules (caching, serializer, transporter) are pluggable
  • Open source - Moleculer is 100% open source and free of charge
  • Fault tolerant - With built-in load balancer & circuit breaker
Sample of usage:
ServiceBroker broker = new ServiceBroker("node-1");

broker.createService(new Service("math") {
        Action add = ctx -> {
                return ctx.params.get("a").asInteger() + ctx.params.get("b").asInteger();
        };
});

broker.start();

broker.call("math.add", "a", 5, "b", 3).then(rsp -> {
        broker.getLogger().info("Response: " + rsp.asInteger());
});
This project is based on the idea of Moleculer Microservices Framework for Node.js (https://moleculer.services). Special thanks to the Moleculer's project owner (https://github.com/icebob) for the consultations.
  • Field Details

    • SOFTWARE_VERSION

      public static final String SOFTWARE_VERSION
      Version of the Java ServiceBroker API.
      See Also:
    • logger

      protected static final org.slf4j.Logger logger
      SLF4J logger of this class.
    • config

      protected final ServiceBrokerConfig config
      Configuration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker. Use the getConfig method to access this object.
    • services

      protected final ConcurrentHashMap<String,Service> services
      Services which defined and added to the Broker before the boot process.
    • serviceNames

      protected final LinkedHashSet<String> serviceNames
      Service names (keys).
    • middlewares

      protected final LinkedHashSet<Middleware> middlewares
      Middlewares which defined and added to the Broker before the boot process.
    • strategyFactory

      protected StrategyFactory strategyFactory
      Default (round-robin) service invocation factory. Use getConfig().getStrategyFactory() to access this instance.
    • serviceRegistry

      protected ServiceRegistry serviceRegistry
      Implementation of the service registry of the current node. Use getConfig().getServiceRegistry() to access this instance.
      See Also:
    • transporter

      protected Transporter transporter
      Implementation of the Transporter. Use getConfig().getTransporter() to access this instance. Can be null.
  • Constructor Details

  • Method Details

    • builder

      public static ServiceBrokerBuilder builder()
      Creates a new ServiceBrokerBuilder instance. Sample of usage:

      ServiceBroker broker = ServiceBroker.builder().cacher(cacher).build();
      Returns:
      builder instance
    • getProtocolVersion

      public String getProtocolVersion()
      Returns the version of the implemented Moleculer Protocol. The value comes from ServiceBrokerConfig.getProtocolVersion() (configurable via ServiceBrokerBuilder.protocolVersion(String) or ServiceBrokerConfig.setProtocolVersion(String)), which is seeded from the "moleculer.protocol.version" System Property and otherwise defaults to ServiceBrokerConfig.DEFAULT_PROTOCOL_VERSION ("5", matching Moleculer JS 0.15).
      Returns:
      version of the implemented protocol (eg. "5")
    • getConfig

      public ServiceBrokerConfig getConfig()
      Returns the configuration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker.
      Returns:
      configuration container
    • getNodeID

      public String getNodeID()
      Returns the unique ContextSource.nodeID of this node (~= ServiceBroker instance).
      Returns:
      unique ContextSource.nodeID
    • start

      public ServiceBroker start() throws Exception
      Start broker. If has a Transporter, transporter.connect() will be called.
      Returns:
      this ServiceBroker instance (from "method chaining")
      Throws:
      Exception - fatal error (missing classes or JARs, used port, etc.)
    • initJsonReader

      protected void initJsonReader()
      Set global JSON reader API (Jackson, Gson, Boon, FastJson, etc.).
    • initJsonWriter

      protected void initJsonWriter()
      Set global JSON writer API (Jackson, Gson, Boon, FastJson, etc.)
    • start

      protected <TYPE extends MoleculerLifecycle> TYPE start(TYPE component) throws Exception
      Starts the specified MoleculerComponent.
      Type Parameters:
      TYPE - Moleculer component (service registry, transporter, etc.)
      Parameters:
      component - component to start
      Returns:
      the started component
      Throws:
      Exception - any configuration or I/O exceptions
    • stop

      public ServiceBroker stop()
      Stop broker and all internal components (event bus, context factory, etc.). If the Broker has a Transporter, transporter.disconnect() will be called.
      Returns:
      this ServiceBroker instance (from "method chaining")
    • stop

      protected void stop(MoleculerComponent component)
      Stops the specified MoleculerComponent.
      Parameters:
      component - component to stop
    • getLogger

      public org.slf4j.Logger getLogger()
      Returns the SLF4J logger of this broker instance.
      Returns:
      logger instance
    • getLogger

      public org.slf4j.Logger getLogger(Class<?> clazz)
      Returns a logger named corresponding to the class passed as parameter.
      Parameters:
      clazz - the returned logger will be named after clazz
      Returns:
      logger instance
    • getLogger

      public org.slf4j.Logger getLogger(String name)
      Return a logger named according to the name parameter.
      Parameters:
      name - the name of the logger
      Returns:
      logger instance
    • createService

      public ServiceBroker createService(Service service)
      Installs a new service instance and notifies other nodes about the actions/listeners of the new service.
      Parameters:
      service - the new service instance
      Returns:
      this ServiceBroker instance (from "method chaining")
    • createService

      public ServiceBroker createService(String name, Service service)
      Installs a new service with the specified name (eg. "user" service) and notifies other nodes about the actions/listeners of this new service.
      Parameters:
      name - custom service name (eg. "user", "logger", "configurator", etc.)
      service - the new service instance
      Returns:
      this ServiceBroker instance (from "method chaining")
    • broadcastServicesChanged

      protected void broadcastServicesChanged()
    • getLocalService

      public Service getLocalService(String serviceName)
      Returns a local service by name (eg. "user" service).
      Parameters:
      serviceName - service name (eg. "user", "logger", "configurator", etc.)
      Returns:
      local service instance
      Throws:
      NoSuchElementException - if the service name is not valid
    • use

      public ServiceBroker use(Collection<Middleware> middlewares)
      Installs a collection of middlewares.
      Parameters:
      middlewares - collection of middlewares
      Returns:
      this ServiceBroker instance (from "method chaining")
    • use

      public ServiceBroker use(Middleware... middlewares)
      Installs one or an array of middleware(s).
      Parameters:
      middlewares - array of middlewares
      Returns:
      this ServiceBroker instance (from "method chaining")
    • getAction

      public Action getAction(String actionName)
      Returns an action by name.
      Parameters:
      actionName - name of the action (in "service.action" syntax, eg. "math.add")
      Returns:
      local or remote action container
    • getAction

      public Action getAction(String actionName, String nodeID)
      Returns an action by name and nodeID.
      Parameters:
      actionName - name of the action (in "service.action" syntax, eg. "math.add")
      nodeID - node identifier where the service is located
      Returns:
      local or remote action container
    • waitForServices

      public io.datatree.Promise waitForServices(String... services)
      Waits for one or more services. Sample code:

      broker.waitForServices("logger", "printer").then(in -> {
      broker.getLogger().info("Logger and printer started");
      }
      Parameters:
      services - service names
      Returns:
      a listenable Promise
    • waitForServices

      public io.datatree.Promise waitForServices(long timeoutMillis, String... services)
      Waits for one (or an array of) service(s). Sample code:

      broker.waitForServices(5000, "logger").then(in -> {
      broker.getLogger().info("Logger started successfully");
      }.catchError(error -> {
      broker.getLogger().info("Logger did not start");
      }
      Parameters:
      timeoutMillis - timeout in milliseconds
      services - array of service names
      Returns:
      listenable Promise
    • waitForServices

      public io.datatree.Promise waitForServices(long timeoutMillis, Collection<String> services)
      Waits for a collection of services. Sample code:

      Set<String> serviceNames = ...
      broker.waitForServices(5000, serviceNames).then(in -> {
      broker.getLogger().info("Ok");
      }.catchError(error -> {
      broker.getLogger().info("Failed / timeout");
      }
      Parameters:
      timeoutMillis - timeout in milliseconds
      services - collection of service names
      Returns:
      listenable Promise
    • ping

      public io.datatree.Promise ping(String nodeID)
      Sends a PING message to the specified node. The ping timeout is 3 seconds. Sample:

      broker.ping("node2").then(in -> {
      broker.getLogger().info("Ok");
      }.catchError(error -> {
      broker.getLogger().info("Ping timeouted");
      }
      Parameters:
      nodeID - node ID of the destination node
      Returns:
      listenable Promise
    • ping

      public io.datatree.Promise ping(long timeoutMillis, String nodeID)
      Sends a PING message to the specified node. Sample:

      broker.ping(5000, "node2").then(in -> {
      broker.getLogger().info("Ok");
      }.catchError(error -> {
      broker.getLogger().info("Ping timeouted");
      }
      Parameters:
      timeoutMillis - ping timeout in milliseconds
      nodeID - node ID of the destination node
      Returns:
      listenable Promise
    • repl

      public boolean repl()
      Starts a local (System in/out) developer console. You must install "moleculer-java-repl" dependency for use this feature.
      Returns:
      true if started
    • repl

      public boolean repl(boolean local)
      Starts a local (System in/out) or a remote (telnet-based) developer console. You must install "moleculer-java-repl" dependency to use this feature.
      Parameters:
      local - true = local console, false = telnet-based console
      Returns:
      true if started