Class ServiceBroker
java.lang.Object
services.moleculer.context.ContextSource
services.moleculer.ServiceBroker
- All Implemented Interfaces:
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
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 Summary
FieldsModifier and TypeFieldDescriptionprotected final ServiceBrokerConfigConfiguration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker.protected static final org.slf4j.LoggerSLF4J logger of this class.protected final LinkedHashSet<Middleware> Middlewares which defined and added to the Broker before the boot process.protected final LinkedHashSet<String> Service names (keys).protected ServiceRegistryImplementation of the service registry of the current node.protected final ConcurrentHashMap<String, Service> Services which defined and added to the Broker before the boot process.static final StringVersion of the Java ServiceBroker API.protected StrategyFactoryDefault (round-robin) service invocation factory.protected TransporterImplementation of the Transporter.Fields inherited from class ContextSource
eventbus, nodeID, serviceInvoker, uidGeneratorFields inherited from interface MetricConstants
MOLECULER_CACHER_CLEAN_TIME, MOLECULER_CACHER_CLEAN_TIME_DESC, MOLECULER_CACHER_CLEAN_TOTAL, MOLECULER_CACHER_CLEAN_TOTAL_DESC, MOLECULER_CACHER_DEL_TIME, MOLECULER_CACHER_DEL_TIME_DESC, MOLECULER_CACHER_DEL_TOTAL, MOLECULER_CACHER_DEL_TOTAL_DESC, MOLECULER_CACHER_EXPIRED_TOTAL, MOLECULER_CACHER_EXPIRED_TOTAL_DESC, MOLECULER_CACHER_FOUND_TOTAL, MOLECULER_CACHER_FOUND_TOTAL_DESC, MOLECULER_CACHER_GET_TIME, MOLECULER_CACHER_GET_TIME_DESC, MOLECULER_CACHER_GET_TOTAL, MOLECULER_CACHER_GET_TOTAL_DESC, MOLECULER_CACHER_SET_TIME, MOLECULER_CACHER_SET_TIME_DESC, MOLECULER_CACHER_SET_TOTAL, MOLECULER_CACHER_SET_TOTAL_DESC, MOLECULER_CIRCUIT_BREAKER_HALF_OPENED_ACTIVE, MOLECULER_CIRCUIT_BREAKER_HALF_OPENED_ACTIVE_DESC, MOLECULER_CIRCUIT_BREAKER_OPENED_ACTIVE, MOLECULER_CIRCUIT_BREAKER_OPENED_ACTIVE_DESC, MOLECULER_CIRCUIT_BREAKER_OPENED_TOTAL, MOLECULER_CIRCUIT_BREAKER_OPENED_TOTAL_DESC, MOLECULER_EVENT_BROADCAST_TOTAL, MOLECULER_EVENT_BROADCAST_TOTAL_DESC, MOLECULER_EVENT_BROADCASTLOCAL_TOTAL, MOLECULER_EVENT_BROADCASTLOCAL_TOTAL_DESC, MOLECULER_EVENT_EMIT_TOTAL, MOLECULER_EVENT_EMIT_TOTAL_DESC, MOLECULER_EVENT_RECEIVED_ACTIVE, MOLECULER_EVENT_RECEIVED_ACTIVE_DESC, MOLECULER_EVENT_RECEIVED_ERROR_TOTAL, MOLECULER_EVENT_RECEIVED_ERROR_TOTAL_DESC, MOLECULER_EVENT_RECEIVED_TIME, MOLECULER_EVENT_RECEIVED_TIME_DESC, MOLECULER_EVENT_RECEIVED_TOTAL, MOLECULER_EVENT_RECEIVED_TOTAL_DESC, MOLECULER_EXECUTOR, MOLECULER_REQUEST_ACTIVE, MOLECULER_REQUEST_ACTIVE_DESC, MOLECULER_REQUEST_ERROR_TOTAL, MOLECULER_REQUEST_ERROR_TOTAL_DESC, MOLECULER_REQUEST_LEVELS, MOLECULER_REQUEST_LEVELS_DESC, MOLECULER_REQUEST_RETRY_ATTEMPTS_TOTAL, MOLECULER_REQUEST_RETRY_ATTEMPTS_TOTAL_DESC, MOLECULER_REQUEST_TIME, MOLECULER_REQUEST_TIME_DESC, MOLECULER_REQUEST_TIMEOUT_TOTAL, MOLECULER_REQUEST_TIMEOUT_TOTAL_DESC, MOLECULER_REQUEST_TOTAL, MOLECULER_REQUEST_TOTAL_DESC, MOLECULER_SCHEDULER, MOLECULER_TRANSIT_CONNECTED, MOLECULER_TRANSIT_CONNECTED_DESC, MOLECULER_TRANSIT_ORPHAN_RESPONSE_TOTAL, MOLECULER_TRANSIT_ORPHAN_RESPONSE_TOTAL_DESC, MOLECULER_TRANSIT_REQUESTS_ACTIVE, MOLECULER_TRANSIT_REQUESTS_ACTIVE_DESC, MOLECULER_TRANSIT_STREAMS_RECEIVE_ACTIVE, MOLECULER_TRANSIT_STREAMS_RECEIVE_ACTIVE_DESC, MOLECULER_TRANSPORTER_PACKETS_RECEIVED_BYTES, MOLECULER_TRANSPORTER_PACKETS_RECEIVED_BYTES_DESC, MOLECULER_TRANSPORTER_PACKETS_RECEIVED_TOTAL, MOLECULER_TRANSPORTER_PACKETS_RECEIVED_TOTAL_DESC, MOLECULER_TRANSPORTER_PACKETS_SENT_BYTES, MOLECULER_TRANSPORTER_PACKETS_SENT_BYTES_DESC, MOLECULER_TRANSPORTER_PACKETS_SENT_TOTAL, MOLECULER_TRANSPORTER_PACKETS_SENT_TOTAL_DESC -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new ServiceBroker withoutTransporter.ServiceBroker(String nodeID) Creates a new ServiceBroker withoutTransporterand with the specifiedContextSource.nodeID.ServiceBroker(String nodeID, Cacher cacher, Transporter transporter) ServiceBroker(ServiceBrokerConfig config) Creates a new ServiceBroker by the specifiedconfiguration. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidstatic ServiceBrokerBuilderbuilder()Creates a newServiceBrokerBuilderinstance.createService(String name, Service service) Installs a new service with the specified name (eg.createService(Service service) Installs a new service instance and notifies other nodes about the actions/listeners of the new service.Returns an action by name.Returns an action by name and nodeID.Returns the configuration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker.getLocalService(String serviceName) Returns a local service by name (eg.org.slf4j.LoggerReturns the SLF4J logger of this broker instance.org.slf4j.LoggerReturns a logger named corresponding to the class passed as parameter.org.slf4j.LoggerReturn a logger named according to the name parameter.Returns the uniqueContextSource.nodeIDof this node (~= ServiceBroker instance).Returns the version of the implemented Moleculer Protocol.protected voidSet global JSON reader API (Jackson, Gson, Boon, FastJson, etc.).protected voidSet global JSON writer API (Jackson, Gson, Boon, FastJson, etc.)io.datatree.PromiseSends a PING message to the specified node.io.datatree.PromiseSends a PING message to the specified node.booleanrepl()Starts a local (System in/out) developer console.booleanrepl(boolean local) Starts a local (System in/out) or a remote (telnet-based) developer console.start()Start broker.protected <TYPE extends MoleculerLifecycle>
TYPEstart(TYPE component) Starts the specifiedMoleculerComponent.stop()Stop broker and all internal components (event bus, context factory, etc.).protected voidstop(MoleculerComponent component) Stops the specifiedMoleculerComponent.use(Collection<Middleware> middlewares) Installs a collection of middlewares.use(Middleware... middlewares) Installs one or an array of middleware(s).io.datatree.PromisewaitForServices(long timeoutMillis, String... services) Waits for one (or an array of) service(s).io.datatree.PromisewaitForServices(long timeoutMillis, Collection<String> services) Waits for a collection of services.io.datatree.PromisewaitForServices(String... services) Waits for one or more services.Methods inherited from class ContextSource
broadcast, broadcast, broadcast, broadcast, broadcast, broadcast, broadcastLocal, broadcastLocal, broadcastLocal, call, call, call, call, call, call, createStream, emit, emit, emit, emit, emit, emit
-
Field Details
-
SOFTWARE_VERSION
-
logger
protected static final org.slf4j.Logger loggerSLF4J logger of this class. -
config
Configuration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker. Use thegetConfigmethod to access this object. -
services
Services which defined and added to the Broker before the boot process. -
serviceNames
Service names (keys). -
middlewares
Middlewares which defined and added to the Broker before the boot process. -
strategyFactory
Default (round-robin) service invocation factory. UsegetConfig().getStrategyFactory()to access this instance. -
serviceRegistry
Implementation of the service registry of the current node. UsegetConfig().getServiceRegistry()to access this instance.- See Also:
-
transporter
Implementation of the Transporter. UsegetConfig().getTransporter()to access this instance. Can benull.
-
-
Constructor Details
-
ServiceBroker
Creates a new ServiceBroker by the specifiedconfiguration.- Parameters:
config- configuration of the Broker
-
ServiceBroker
public ServiceBroker()Creates a new ServiceBroker withoutTransporter. TheContextSource.nodeIDis generated from the host name and process ID. -
ServiceBroker
Creates a new ServiceBroker withoutTransporterand with the specifiedContextSource.nodeID.- Parameters:
nodeID- the uniqueContextSource.nodeIDof this node
-
ServiceBroker
- Parameters:
nodeID- the uniqueContextSource.nodeIDof this nodecacher-Cacherof this broker instancetransporter-Transporterof this broker instance
-
-
Method Details
-
builder
Creates a newServiceBrokerBuilderinstance. Sample of usage:
ServiceBroker broker = ServiceBroker.builder().cacher(cacher).build();- Returns:
- builder instance
-
getProtocolVersion
Returns the version of the implemented Moleculer Protocol. The value comes fromServiceBrokerConfig.getProtocolVersion()(configurable viaServiceBrokerBuilder.protocolVersion(String)orServiceBrokerConfig.setProtocolVersion(String)), which is seeded from the "moleculer.protocol.version" System Property and otherwise defaults toServiceBrokerConfig.DEFAULT_PROTOCOL_VERSION("5", matching Moleculer JS 0.15).- Returns:
- version of the implemented protocol (eg. "5")
-
getConfig
Returns the configuration settings and internal components (event bus, cacher, service registry, etc.) of this node / broker.- Returns:
- configuration container
-
getNodeID
Returns the uniqueContextSource.nodeIDof this node (~= ServiceBroker instance).- Returns:
- unique
ContextSource.nodeID
-
start
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
Starts the specifiedMoleculerComponent.- 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
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
Stops the specifiedMoleculerComponent.- Parameters:
component- component to stop
-
getLogger
public org.slf4j.Logger getLogger()Returns the SLF4J logger of this broker instance.- Returns:
- logger instance
-
getLogger
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
Return a logger named according to the name parameter.- Parameters:
name- the name of the logger- Returns:
- logger instance
-
createService
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
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
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
Installs a collection of middlewares.- Parameters:
middlewares- collection of middlewares- Returns:
- this ServiceBroker instance (from "method chaining")
-
use
Installs one or an array of middleware(s).- Parameters:
middlewares- array of middlewares- Returns:
- this ServiceBroker instance (from "method chaining")
-
getAction
-
getAction
-
waitForServices
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
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 millisecondsservices- array of service names- Returns:
- listenable Promise
-
waitForServices
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 millisecondsservices- collection of service names- Returns:
- listenable Promise
-
ping
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
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 millisecondsnodeID- 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
-