To install the service in our Wildfly nodes we need to write an activator class. Here an example of Activator class:
public class HAServiceActivator implements ServiceActivator {
@Override
public void activate(ServiceActivatorContext context) {
...
}
}
The activate method is started during the start of Wildfly. An activator class must implement the org.jboss.msc.service.ServiceActivator interface. Here a sample of activate implementation:
...
ServiceTarget target = context.getServiceTarget();
try {
SingletonServiceBuilderFactory factory = (SingletonServiceBuilderFactory) context.getServiceRegistry()
.getRequiredService(BUILDER.getServiceName("server")).awaitValue();
install(target, factory, DEFAULT_SERVICE_NAME, 1);
install(target, factory, QUORUM_SERVICE_NAME, 2);
} catch (InterruptedException e) {
throw new ServiceRegistryException(e);
}
In this sample we take the org.jboss.msc.service.ServiceTarget instance through the injected context org.jboss.msc.service.ServiceActivatorContext. Through the ServiceTarget we take the org.wildfly.clustering.singleton.SingletonServiceBuilderFactory instance passing the default name for the Wildfly instances, server. This factory is responsible for the creation of the HA Singletons.
Through a custom install method we will install two HA Singletons (default and quorum) called through the org.jboss.msc.service.ServiceName interface. Here the declarations of the two services:
public static final ServiceName DEFAULT_SERVICE_NAME = JBOSS.append("test", "haservice", "default");
public static final ServiceName QUORUM_SERVICE_NAME = JBOSS.append("test", "haservice", "quorum");
Here the install method:
private static void install(ServiceTarget target, SingletonServiceBuilderFactory factory, ServiceName name,int quorum) {
InjectedValue<ServerEnvironment> env = new InjectedValue<>();
HAService service = new HAService(env);
factory.createSingletonServiceBuilder(name, service)
.electionPolicy(new PreferredSingletonElectionPolicy(new SimpleSingletonElectionPolicy(),new NamePreference(PREFERRED_NODE)))
.requireQuorum(quorum).build(target).addDependency(SERVICE_NAME, ServerEnvironment.class, env).install();
}
Through the SingletonServiceBuilderFactory we:
- Create the default Singleton Service Builder represented by the org.wildfly.clustering.singleton.SingletonServiceBuilder interface through the createSingletonServiceBuilder method.
- Can customize the election policy shown over declaring an alternative policy class through the electionPolicy method.
- Declare the the minimum number of members required before a singleton master election will take place through the requireQuorum method.
- Build the service through the build method
- Add additional class dependencies through the addDependency method. In this case we add the ServerEnvironment class useful to the service to receive the server node informations
- Install the service through the install method.