§Understanding Hello World
After creating and running Hello World from the command line, you no doubt appreciate what Lagom framework did for you. There was no need to determine what infrastructure you might need and then install and configure it. The template removed the necessity to set up a project or build structure. And, as you create services of your own, Lagom detects changes and performs a hot reload! Lagom allows you to concentrate on satisfying your business needs.
The separation of concerns illustrated in Hello World and an introduction to service descriptors and the registry will help you as you start developing your own microservices:
§Service interface
The source file defining a service interface belongs in the service’s api project. For example, in Hello World, HelloService.java, the source file for the hello service interface resides in the hello-api directory of the Maven project or sbt build.
public interface HelloService extends Service {
ServiceCall<NotUsed, String> hello(String id);
@Override
default Descriptor descriptor() {
return named("helloservice").withCalls(
restCall(Method.GET, "/api/hello/:id", this::hello)
).withAutoAcl(true);
}
}
Note that:
-
The service interface inherits from
Serviceand provides an implementation ofService.descriptormethod. -
The implementation of
Service.descriptorreturns aDescriptor. TheHelloServicedescriptor defines the service name and the REST endpoints it offers. For each endpoint, declare an abstract method in the service interface, as illustrated in theHelloService.hellomethod. For more information, see Service Descriptors.
§Service implementation
The related impl directory contains the implementation of the service interface’s abstract methods. For instance, HelloServiceImpl.java in the hello-impl directory implements the hello service HelloService.hello method. It includes the PersistentEntityRegistry, which allows you to persist data in the database using Event Sourcing and CQRS.
public class HelloServiceImpl implements HelloService {
private final PersistentEntityRegistry persistentEntityRegistry;
@Inject
public HelloServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
this.persistentEntityRegistry = persistentEntityRegistry;
persistentEntityRegistry.register(HelloWorld.class);
}
@Override
public ServiceCall<NotUsed, String> hello(String id) {
return request -> {
// Look up the hello world entity for the given ID.
PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloWorld.class, id);
// Ask the entity the Hello command.
return ref.ask(new Hello(id, Optional.empty()));
};
}
}