Database service interface
Defining a service interface is as simple as defining a Java interface, except that there are certain rules to respect for code generation to work and also to ensure inter-operability with other code in Vert.x.
The beginning of the interface definition is:
@ProxyGen
@VertxGen
public interface WikiDatabaseService {
@Fluent
WikiDatabaseService fetchAllPages(Handler<AsyncResult<JsonArray>> resultHandler);
@Fluent
WikiDatabaseService fetchPage(String name, Handler<AsyncResult<JsonObject>> resultHandler);
@Fluent
WikiDatabaseService createPage(String title, String markdown, Handler<AsyncResult<Void>> resultHandler);
@Fluent
WikiDatabaseService savePage(int id, String markdown, Handler<AsyncResult<Void>> resultHandler);
@Fluent
WikiDatabaseService deletePage(int id, Handler<AsyncResult<Void>> resultHandler);
// (...)
The
ProxyGen
annotation is used to trigger the code generation of a proxy for clients of that service.The
Fluent
annotation is optional, but allows fluent interfaces where operations can be chained by returning the service instance. This is mostly useful for the code generator when the service shall be consumed from other JVM languages.Parameter types need to be strings, Java primitive types, JSON objects or arrays, any enumeration type or a
java.util
collection (List
/Set
/Map
) of the previous types. The only way to support arbitrary Java classes is to have them as Vert.x data objects, annotated with@DataObject
. The last opportunity to pass other types is service reference types.Since services provide asynchronous results, the last argument of a service method needs to be a
Handler<AsyncResult<T>>
whereT
is any of the types suitable for code generation as described above.
It is a good practice that service interfaces provide static methods to create instances of both the actual service implementation and proxy for client code over the event bus.
We define create
as simply delegating to the implementation class and its constructor:
@GenIgnore
static WikiDatabaseService create(JDBCClient dbClient, HashMap<SqlQuery, String> sqlQueries, Handler<AsyncResult<WikiDatabaseService>> readyHandler) {
return new WikiDatabaseServiceImpl(dbClient, sqlQueries, readyHandler);
}
The Vert.x code generator creates the proxy class and names it by suffixing with VertxEBProxy
. Constructors of these proxy classes need a reference to the Vert.x context as well as a destination address on the event bus:
@GenIgnore
static WikiDatabaseService createProxy(Vertx vertx, String address) {
return new WikiDatabaseServiceVertxEBProxy(vertx, address);
}
Note | The SqlQuery and ErrorCodes enumeration types that were inner classes in the previous iteration have been extracted to package-protected types, see SqlQuery.java and ErrorCodes.java . |