此内容没有您所选择的语言版本。
Eclipse Vert.x 4.2 Migration Guide
For use with Eclipse Vert.x 4.2
Abstract
Preface 复制链接链接已复制到粘贴板!
This guide describes the updates in Eclipse Vert.x 4 release. Use the information to upgrade your Eclipse Vert.x 3.x applications to Eclipse Vert.x 4. It provides information about the new, deprecated and unsupported features in this release.
Depending on the modules used in your application, you can read the relevant section to know more about the changes in Eclipse Vert.x 4.
Providing feedback on Red Hat documentation 复制链接链接已复制到粘贴板!
We appreciate your feedback on our documentation. To provide feedback, you can highlight the text in a document and add comments.
This section explains how to submit feedback.
Prerequisites
- You are logged in to the Red Hat Customer Portal.
- In the Red Hat Customer Portal, view the document in Multi-page HTML format.
Procedure
To provide your feedback, perform the following steps:
Click the Feedback button in the top-right corner of the document to see existing feedback.
NoteThe feedback feature is enabled only in the Multi-page HTML format.
- Highlight the section of the document where you want to provide feedback.
Click the Add Feedback pop-up that appears near the highlighted text.
A text box appears in the feedback section on the right side of the page.
Enter your feedback in the text box and click Submit.
A documentation issue is created.
- To view the issue, click the issue tracker link in the feedback view.
Making open source more inclusive 复制链接链接已复制到粘贴板!
Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message.
When you start configuring your applications to use Eclipse Vert.x, you must reference the Eclipse Vert.x BOM (Bill of Materials) artifact in the pom.xml file at the root directory of your application. The BOM is used to set the correct versions of the artifacts.
Prerequisites
- A Maven-based application
Procedure
Open the
pom.xmlfile, add theio.vertx:vertx-dependenciesartifact to the<dependencyManagement>section. Specify thetypeaspomandscopeasimport.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Include the following properties to track the version of Eclipse Vert.x and the Eclipse Vert.x Maven Plugin you are using.
Properties can be used to set values that change in every release. For example, versions of product or plugins.
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Specify
vertx-maven-pluginas the plugin used to package your application:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Include
repositoriesandpluginRepositoriesto specify the repositories that contain the artifacts and plugins to build your application:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Additional resources
- For more information about packaging your Eclipse Vert.x application, see the Vert.x Maven Plugin documentation.
Chapter 2. About Eclipse Vert.x 复制链接链接已复制到粘贴板!
Eclipse Vert.x is a toolkit used for creating reactive, non-blocking, and asynchronous applications that run on Java Virtual Machine. (JVM). It contains several components that help you create reactive applications. It is designed to be cloud-native.
Since Eclipse Vert.x supports asynchronous applications it can be used to create applications with high volume of messages, large event processing, HTTP interactions, and so on.
Chapter 3. What’s changed in Eclipse Vert.x 4 复制链接链接已复制到粘贴板!
This section explains the fundamental differences between Eclipse Vert.x 4 and 3.x releases.
3.1. Use future methods for asynchronous operations 复制链接链接已复制到粘贴板!
Eclipse Vert.x 4 uses futures for asynchronous operations. Every callback method has a corresponding future method. Futures can be used to compose asynchronous operations. You can use a combination of callback and future methods to migrate callback-based applications to Eclipse Vert.x 4. However, you can also continue using callbacks for asynchronous operations.
The following example shows how a callback was used for asynchronous operations in Eclipse Vert.x 3.x releases.
The following example shows how to use callback and future methods together for asynchronous operations in Eclipse Vert.x 4.
Error handling is better with futures. In callbacks, you have to handle failures at every stage of the composition, whereas in futures you can handle the failure once in the end. In basic applications, you may not notice distinct difference between using callbacks and futures.
The following example shows how callbacks can be used to compose two asynchronous operations. You can see that the error is handled at every composition.
The following example shows how callbacks and futures can be used to compose two asynchronous operations in Eclipse Vert.x 4. The error is handled only once in the end.
3.2. No dependency on the Jackson Databind library 复制链接链接已复制到粘贴板!
The JSON features in Eclipse Vert.x depend on Jackson library. Jackson Databind library enables object mapping of JSON.
In Eclipse Vert.x 4, Jackson Databind is an optional Maven dependency. If you want to use this dependency, you must explicitly add it in the classpath.
If you are object mapping JSON, then you must explicitly add the dependency in your project descriptor in the
com.fasterxml.jackson.core:jackson-databindjar.Copy to Clipboard Copied! Toggle word wrap Toggle overflow In future, if you decide not to use object mapping of JSON, you can remove this dependency.
- If you are not object mapping JSON, the Jackson Databind library is not required. You can run your applications without this jar.
3.3. Handling deprecations and removals 复制链接链接已复制到粘贴板!
Some features and functions have been deprecated or removed in Eclipse Vert.x 4. Before you migrate your applications to Eclipse Vert.x 4, check for deprecations and removals.
- Some APIs were deprecated in an Eclipse Vert.x 3.x release and new equivalent APIs were provided in that release.
- The deprecated APIs have been removed in Eclipse Vert.x 4.
If your application uses a deprecated API, you should update your application to use the new API. This helps in migrating applications to the latest version of the product.
The Java compiler generates warnings when deprecated APIs are used. You can use the compiler to check for deprecated methods while migrating applications to Eclipse Vert.x 4.
The following example shows an EventBus method that was deprecated in an Eclipse Vert.x 3.x releases.
// Send was deprecated in Vert.x 3.x release
vertx.eventBus().send("some-address", "hello world", ar -> {
// Handle response here
});
// Send was deprecated in Vert.x 3.x release
vertx.eventBus().send("some-address", "hello world", ar -> {
// Handle response here
});
The method send(String,String,Handler<AsyncResult<Message>>) has been replaced in Eclipse Vert.x 4 with the method request(String,String,Handler<AsyncResult<Message>>).
The following example shows how to update your application to use the new method.
// New method can be used in Vert.x 3.x and Vert.x 4.x releases
vertx.eventBus().request("some-address", "hello world", ar -> {
// Handle response here
});
// New method can be used in Vert.x 3.x and Vert.x 4.x releases
vertx.eventBus().request("some-address", "hello world", ar -> {
// Handle response here
});
Chapter 4. Changes in common components 复制链接链接已复制到粘贴板!
This section explains the changes in basic Eclipse Vert.x components.
4.1. Changes in messaging 复制链接链接已复制到粘贴板!
This section explains the changes in the messaging methods.
The WriteStream<T>.write() and WriteStream<T>.end() methods are no longer fluent.
-
Write and end callback methods return
void. -
Other write and end methods return
Future<Void>.
This is a breaking change. Update your applications if you have used the fluent aspect for write streams.
4.1.2. MessageProducer does not extend WriteStream 复制链接链接已复制到粘贴板!
The MessageProducer interface does not extend the WriteStream interface.
In the previous releases of Eclipse Vert.x, the MessageProducer interface extended the WriteStream interface. The MessageProducer interface provided limited support for message back-pressure. Credit leaks would result in a reduction of credits in the message producer. If these leaks used all the credits, messages would not be sent.
However, MessageConsumer will continue to extend ReadStream. When MessageConsumer is paused and the pending message queue is full, the messages are dropped. This continues the integration with Rx generators to build message consuming pipelines.
4.1.3. Removed the send methods from MessageProducer 复制链接链接已复制到粘贴板!
The send methods in the MessageProducer interface have been removed.
Use the methods MessageProducer<T>.write(T) instead of MessageProducer<T>.send(T) and EventBus.request(String,Object,Handler) instead of MessageProducer.send(T,Handler).
4.2. Changes in EventBus 复制链接链接已复制到粘贴板!
The following section describes the changes in EventBus.
The EventBus.send(…, Handler<AsyncResult<Message<T>>>) and Message.reply(…, Handler<AsyncResult<Message<T>>>) methods have been removed. These methods would have caused overloading issues in Eclipse Vert.x 4. The version of the method returning Future<Message<T>> would collide with the fire and forget version.
The request-response messaging pattern should use the new request and replyAndRequest methods.
-
Use the method
EventBus.request(…, Handler<AsyncResult<Message<T>>>)instead ofEventBus.send(…, Handler<AsyncResult<Message<T>>>)to send a message. -
Use the method
Message.replyAndRequest(…, Handler<AsyncResult<Message<T>>>)instead ofMessage.reply(…, Handler<AsyncResult<Message<T>>>)to reply to the message.
The following example shows the request and reply to a message in Eclipse Vert.x 3.x releases.
- Request
eventBus.send("the-address", body, ar -> ...);
eventBus.send("the-address", body, ar -> ...);
- Reply
eventBus.consumer("the-address", message -> {
message.reply(body, ar -> ...);
});
eventBus.consumer("the-address", message -> {
message.reply(body, ar -> ...);
});
The following example shows the request and reply to a message in Eclipse Vert.x 4.
- Request
eventBus.request("the-address", body, ar -> ...);
eventBus.request("the-address", body, ar -> ...);
- Reply
eventBus.consumer("the-address", message -> {
message.replyAndRequest(body, ar -> ...);
});
eventBus.consumer("the-address", message -> {
message.replyAndRequest(body, ar -> ...);
});
4.3. Changes in future 复制链接链接已复制到粘贴板!
This section explains the changes in future.
4.3.1. Support for multiple handlers for futures 复制链接链接已复制到粘贴板!
From Eclipse Vert.x 4 onward, multiple handlers are supported for a future. The Future<T>.setHandler() method used to set a single handler and has been removed. Use Future<T>.onComplete(), Future<T>.onSuccess(), and Future<T>.onFailure() methods instead to call handlers on completion, success, and failure results of an action.
The following example shows how to call a handler in Eclipse Vert.x 3.x releases.
Future<String> fut = getSomeFuture(); fut.setHandler(ar -> ...);
Future<String> fut = getSomeFuture();
fut.setHandler(ar -> ...);
The following example shows how to call the new Future<T>.onComplete() method in Eclipse Vert.x 4.
Future<String> fut = getSomeFuture(); fut.onComplete(ar -> ...);
Future<String> fut = getSomeFuture();
fut.onComplete(ar -> ...);
4.3.2. Removed the completer() method in future 复制链接链接已复制到粘贴板!
In earlier releases of Eclipse Vert.x, you would use the Future.completer() method to access Handler<AsyncResult<T>>, which was associated with the Future.
In Eclipse Vert.x 4, the Future<T>.completer() method has been removed. Future<T> directly extends Handler<AsyncResult<T>>. You can access all the handler methods using the Future object. The Future object is also a handler.
The HttpClientRequest.connectionHandler() method has been removed. Use HttpClient.connectionHandler() method instead to call connection handlers for client requests in your application.
The following example shows how the HttpClientRequest.connectionHandler() method was used in Eclipse Vert.x 3.x releases.
client.request().connectionHandler(conn -> {
// Connection related code
}).end();
client.request().connectionHandler(conn -> {
// Connection related code
}).end();
The following example shows you how to use the new HttpClient.connectionHandler() method in Eclipse Vert.x 4.
client.connectionHandler(conn -> {
// Connection related code
});
client.connectionHandler(conn -> {
// Connection related code
});
4.4. Changes in verticles 复制链接链接已复制到粘贴板!
This section explains the changes in the verticles.
4.4.1. Updates in the create verticle method 复制链接链接已复制到粘贴板!
In earlier releases of Eclipse Vert.x, VerticleFactory.createVerticle() method synchronously instantiated a verticle. From Eclipse Vert.x 4 onward, the method asynchronously instantiates the verticle and returns the callback Callable<Verticle> instead of the single verticle instance. This improvement enables the application to call this method once and invoke the returned callable multiple times for creating multiple instances.
The following code shows how verticles were instantiated in Eclipse Vert.x 3.x releases.
Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception;
Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception;
The following code shows how verticles are instantiated in Eclipse Vert.x 4.
void createVerticle(String verticleName, ClassLoader classLoader, Promise<Callable<Verticle>> promise);
void createVerticle(String verticleName, ClassLoader classLoader, Promise<Callable<Verticle>> promise);
4.4.2. Updates in the factory class and methods 复制链接链接已复制到粘贴板!
The VerticleFactory class has been simplified. The class does not require initial resolution of an identifier because the factory can instead use nested deployment to deploy the verticle.
If your existing applications use factories, in Eclipse Vert.x 4 you can update the code to use a callable when a promise completes or fails. The callable can be called several times.
The following example shows existing factories in an Eclipse Vert.x 3.x application.
return new MyVerticle();
return new MyVerticle();
The following example shows how to update existing factories to use promise in Eclipse Vert.x 4.
promise.complete(() -> new MyVerticle());
promise.complete(() -> new MyVerticle());
Use the Vertx.executeBlocking() method, if you want the factory to block code. When the factory receives the blocking code, it should resolve the promise and get the verticle instances from the promise.
4.4.3. Removed the multithreaded worker verticles 复制链接链接已复制到粘贴板!
Multi-threaded worker verticle deployment option has been removed. This feature could only be used with Eclipse Vert.x event-bus. Other Eclipse Vert.x components such as HTTP did not support the feature.
Use the unordered Vertx.executeBlocking() method to achieve the same functionality as multi-threaded worker deployment.
4.5. Changes in threads 复制链接链接已复制到粘贴板!
This section explains the changes in threads.
4.5.1. Context affinity for non Eclipse Vert.x thread 复制链接链接已复制到粘贴板!
The Vertx.getOrCreateContext() method creates a single context for each non Eclipse Vert.x thread. The non Eclipse Vert.x threads are associated with a context the first time a context is created. In earlier releases, a new context was created each time the method was called from a non Eclipse Vert.x thread.
new Thread(() -> {
assertSame(vertx.getOrCreateContext(), vertx.getOrCreateContext());
}).start();
new Thread(() -> {
assertSame(vertx.getOrCreateContext(), vertx.getOrCreateContext());
}).start();
This change does not affect your applications, unless your application implicitly relies on a new context to be created with each invocation.
In the following example the n blocks run concurrently as each blocking code is called on a different context.
for (int i = 0;i < n;i++) {
vertx.executeBlocking(block, handler);
}
for (int i = 0;i < n;i++) {
vertx.executeBlocking(block, handler);
}
To get the same results in Eclipse Vert.x 4, you must update the code:
for (int i = 0;i < n;i++) {
vertx.executeBlocking(block, false, handler);
}
for (int i = 0;i < n;i++) {
vertx.executeBlocking(block, false, handler);
}
4.6. Changes in HTTP 复制链接链接已复制到粘贴板!
This section explains the changes in HTTP methods.
4.6.1. Generic updates in Eclipse Vert.x HTTP methods 复制链接链接已复制到粘贴板!
The following section describes the miscellaneous updates in Eclipse Vert.x HTTP methods.
4.6.1.1. Updates in HTTP Methods for WebSocket 复制链接链接已复制到粘贴板!
The changes in WebSocket are:
The usage of the term
WebSocketin method names was inconsistent. The method names had incorrect capitalization, for example,Websocket, instead ofWebSocket. The methods that had inconsistent usage ofWebSocketin the following classes have been removed. Use the new methods that have correct capitalization instead.The following methods in
HttpServerOptionsclass have been removed.Expand Removed methods New methods getMaxWebsocketFrameSize()getMaxWebSocketFrameSize()setMaxWebsocketFrameSize()setMaxWebSocketFrameSize()getMaxWebsocketMessageSize()getMaxWebSocketMessageSize()setMaxWebsocketMessageSize()setMaxWebSocketMessageSize()getPerFrameWebsocketCompressionSupported()getPerFrameWebSocketCompressionSupported()setPerFrameWebsocketCompressionSupported()setPerFrameWebSocketCompressionSupported()getPerMessageWebsocketCompressionSupported()getPerMessageWebSocketCompressionSupported()setPerMessageWebsocketCompressionSupported()setPerMessageWebSocketCompressionSupported()getWebsocketAllowServerNoContext()getWebSocketAllowServerNoContext()setWebsocketAllowServerNoContext()setWebSocketAllowServerNoContext()getWebsocketCompressionLevel()getWebSocketCompressionLevel()setWebsocketCompressionLevel()setWebSocketCompressionLevel()getWebsocketPreferredClientNoContext()getWebSocketPreferredClientNoContext()setWebsocketPreferredClientNoContext()setWebSocketPreferredClientNoContext()getWebsocketSubProtocols()getWebSocketSubProtocols()setWebsocketSubProtocols()setWebSocketSubProtocols()The new methods for
WebSocketsubprotocols useList<String>data type instead of a comma separated string to store items.The following methods in
HttpClientOptionsclass have been removed.Expand Removed Methods Replacing Methods getTryUsePerMessageWebsocketCompression()getTryUsePerMessageWebSocketCompression()setTryUsePerMessageWebsocketCompression()setTryUsePerMessageWebSocketCompression()getTryWebsocketDeflateFrameCompression()getTryWebSocketDeflateFrameCompression()getWebsocketCompressionAllowClientNoContext()getWebSocketCompressionAllowClientNoContext()setWebsocketCompressionAllowClientNoContext()setWebSocketCompressionAllowClientNoContext()getWebsocketCompressionLevel()getWebSocketCompressionLevel()setWebsocketCompressionLevel()setWebSocketCompressionLevel()getWebsocketCompressionRequestServerNoContext()getWebSocketCompressionRequestServerNoContext()setWebsocketCompressionRequestServerNoContext()setWebSocketCompressionRequestServerNoContext()The following handler methods in
HttpServerclass have been removed.Expand Deprecated Methods New Methods websocketHandler()webSocketHandler()websocketStream()webSocketStream()
-
WebsocketRejectedExceptionis deprecated. The methods throwUpgradeRejectedExceptioninstead. -
The
HttpClientwebSocket()methods useHandler<AsyncResult<WebSocket>>instead ofHandlerorHandler<Throwable>. -
The number of overloaded methods to connect an HTTP client to a WebSocket has also been reduced by using the methods in
WebSocketConnectOptionsclass. The
HttpServerRequest.upgrade()method has been removed. This method was synchronous.Use the new method
HttpServerRequest.toWebSocket()instead. This new method is asynchronous.The following example shows the use of synchronous method in Eclipse Vert.x 3.x.
// 3.x server.requestHandler(req -> { WebSocket ws = req.upgrade(); });// 3.x server.requestHandler(req -> { WebSocket ws = req.upgrade(); });Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following example shows the use of asynchronous method in Eclipse Vert.x 4.
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
4.6.1.2. Setting the number of WebSocket connections 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 3.x, you could use the the HTTP client pool size to define the maximum number of WebSocket connections in an application. The value accessor methods HttpClientOptions.maxPoolSize() were used to get and set the WebSocket connections. The default number of connections was set to 4 for each endpoint.
The following example shows how WebSocket connections are set in Eclipse Vert.x 3.x.
// 3.x options.setMaxPoolSize(30); // Maximum connection is set to 30 for each endpoint
// 3.x
options.setMaxPoolSize(30); // Maximum connection is set to 30 for each endpoint
However, in Eclipse Vert.x 4, there is no pooling of WebSocket TCP connections, because the connections are closed after use. The applications use a different pool for HTTP requests. Use the value accessor methods HttpClientOptions.maxWebSockets() to get and set the WebSocket connections. The default number of connections is set to 50 for each endpoint.
The following example shows how to set WebSocket connections in Eclipse Vert.x 4.
// 4.x options.setMaxWebSockets(30); // Maximum connection is set to 30 for each endpoint
// 4.x
options.setMaxWebSockets(30); // Maximum connection is set to 30 for each endpoint
4.6.1.3. HttpMethod is available as a interface 复制链接链接已复制到粘贴板!
HttpMethod is available as a new interface.
In earlier releases of Eclipse Vert.x, HttpMethod was declared as an enumerated data type. As an enumeration, it limited the extensibility of HTTP. Further, it prevented serving other HTTP methods with this type directly. You had to use the HttpMethod.OTHER value along with the rawMethod attribute during server and client HTTP requests.
If you are using HttpMethod enumerated data type in a switch block, you can use the following code to migrate your applications to Eclipse Vert.x 4.
The following example shows a switch block in Eclipse Vert.x 3.x releases.
The following example shows a switch block in Eclipse Vert.x 4.
You can also use the following code in Eclipse Vert.x 4.
If you are using HttpMethod.OTHER value in your applications, use the following code to migrate the application to Eclipse Vert.x 4.
The following example shows you the code in Eclipse Vert.x 3.x releases.
client.request(HttpMethod.OTHER, ...).setRawName("PROPFIND");
client.request(HttpMethod.OTHER, ...).setRawName("PROPFIND");
The following example shows you the code in Eclipse Vert.x 4.
client.request(HttpMethod.valueOf("PROPFIND"), ...);
client.request(HttpMethod.valueOf("PROPFIND"), ...);
4.6.2. Changes in HTTP client 复制链接链接已复制到粘贴板!
This section describes the changes in HTTP client.
The following types of Eclipse Vert.x clients are available:
- Eclipse Vert.x web client
- Use the Eclipse Vert.x web client when your applications are web oriented. For example, REST, encoding and decoding HTTP payloads, interpreting the HTTP status response code, and so on.
- Eclipse Vert.x HTTP client
- Use the Eclipse Vert.x HTTP client when your applications are used as HTTP proxy. For example, as an API gateway. The HTTP client has been updated and improved in Eclipse Vert.x 4.
Eclipse Vert.x web client is based on Eclipse Vert.x HTTP client.
The web client was available from Eclipse Vert.x 3.4.0 release. There is no change in the web client in Eclipse Vert.x 4.
The client provides simplified HTTP interactions and some additional features, such as HTTP session, JSON encoding and decoding, response predicates, which are not available in the Eclipse Vert.x HTTP Client.
The following example shows how to use HTTP client in Eclipse Vert.x 3.x releases.
The following example shows how to migrate an application to web client in Eclipse Vert.x 3.x and Eclipse Vert.x 4 releases.
The HTTP client has fine grained control over HTTP interactions and focuses on the HTTP protocol.
The HTTP client has been updated and improved in Eclipse Vert.x 4:
- Simplified APIs with fewer interactions
- Robust error handling
- Support for connection reset for HTTP/1
The updates in HTTP client APIs are:
-
The methods in
HttpClientRequestsuch as,get(),delete(),put()have been removed. Use the methodHttpClientRequest> request(HttpMethod method, …)instead. -
HttpClientRequestinstance is created when a request or response is possible. For example, anHttpClientRequestinstance is created when the client connects to the server or a connection is reused from the pool.
4.6.2.2.1. Sending a simple request 复制链接链接已复制到粘贴板!
The following example shows how to send a GET request in Eclipse Vert.x 3.x releases.
The following example shows how to send a GET request in Eclipse Vert.x 4.
You can see that error handling is better in the new HTTP client.
The following example shows how to use future composition in a GET operation in Eclipse Vert.x 4.
Future composition improves exception handling. The example checks if the status code is 200, otherwise it returns an error.
When you use the HTTP client with futures, the HttpClientResponse() method starts emitting buffers as soon as it receives a response. To avoid this, ensure that the future composition occurs either on the event-loop (as shown in the example) or it should pause and resume the response.
4.6.2.2.2. Sending requests 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 3.x releases, you could use the end() method to send requests.
request.end();
request.end();
You could also send a body in the request.
request.end(Buffer.buffer("hello world));
request.end(Buffer.buffer("hello world));
Since HttpClientRequest is a Writestream<Buffer>, you could also use a pipe to stream the request.
writeStream.pipeTo(request, ar -> {
if (ar.succeeded()) {
// Sent the stream
}
});
writeStream.pipeTo(request, ar -> {
if (ar.succeeded()) {
// Sent the stream
}
});
In Eclipse Vert.x 4, you can perform all the operations shown in the examples using the get() method. You can also use the new send() method to perform these operations. You can pass a buffer, a string, or a ReadStream as input to the send() method. The method returns an HttpClientResponse instance.
4.6.2.2.3. Handling responses 复制链接链接已复制到粘贴板!
The HttpClientResponse interface has been updated and improved with the following methods:
body()methodThe
body()method returns an asynchronous buffer. Use thebody()method instead ofbodyHandler().The following example shows how to use the
bodyHandler()method to get the request body.Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following example shows how to use the
body()method to get the request body.Copy to Clipboard Copied! Toggle word wrap Toggle overflow end()methodThe
end()method returns a future when a response is fully received successfully or failed. The method removes the response body. Use this method instead ofendHandler()method.The following example shows how to use the
endHandler()method.Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following example shows how to use the
end()method.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
You can also handle the response with methods such as, onSucces(), compose(), bodyHandler() and so on. The following examples demonstrate handling responses using the onSuccess() method.
The following example shows how to use HTTP client with the result() method in Eclipse Vert.x 3.x releases.
The following example shows how to use HTTP client with the result() method in Eclipse Vert.x 4.
4.6.2.3. Improvements in the Eclipse Vert.x HTTP client 复制链接链接已复制到粘贴板!
This section describes the improvements in HTTP client.
The HttpClient and HttpClientRequest methods have been updated to use asynchronous handlers. The methods take Handler<AsyncResult<HttpClientResponse>> as input instead of Handler<HttpClientResponse>.
In earlier releases of Eclipse Vert.x, the HttpClient methods getNow(), optionsNow() and headNow() used to return HttpClientRequest, that you had to further send to perform a request. The getNow(), optionsNow() and headNow() methods have been removed. In Eclipse Vert.x 4, you can directly send a request with the required information using Handler<AsyncResult<HttpClientResponse>>.
The following examples show how to send a request in Eclipse Vert.x 3.x.
To perform a GET operation:
Future<HttpClientResponse> f1 = client.get(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"));Future<HttpClientResponse> f1 = client.get(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"));Copy to Clipboard Copied! Toggle word wrap Toggle overflow To POST with a buffer body:
Future<HttpClientResponse> f2 = client.post(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"), Buffer.buffer("some-data"));Future<HttpClientResponse> f2 = client.post(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"), Buffer.buffer("some-data"));Copy to Clipboard Copied! Toggle word wrap Toggle overflow To POST with a streaming body:
Future<HttpClientResponse> f3 = client.post(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"), asyncFile);Future<HttpClientResponse> f3 = client.post(8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"), asyncFile);Copy to Clipboard Copied! Toggle word wrap Toggle overflow
In Eclipse Vert.x 4, you can use the requests methods to create an HttpClientRequest instance. These methods can be used in basic interactions such as:
- Sending the request headers
- HTTP/2 specific operations such as setting a push handler, setting stream priority, pings, and so on.
- Creating a NetSocket tunnel
- Providing fine grained write control
- Resetting a stream
- Handling 100 continue headers manually
The following example shows you how to create an HTTPClientRequest in Eclipse Vert.x 4.
The HttpClientRequest.connectionHandler() method has been removed. Use HttpClient.connectionHandler() method instead to call connection handlers for client requests in your application.
The following example shows how the HttpClientRequest.connectionHandler() method was used in Eclipse Vert.x 3.x releases.
client.request().connectionHandler(conn -> {
// Connection related code
}).end();
client.request().connectionHandler(conn -> {
// Connection related code
}).end();
The following example shows you how to use the new HttpClient.connectionHandler() method.
client.connectionHandler(conn -> {
// Connection related code
});
client.connectionHandler(conn -> {
// Connection related code
});
HTTP tunnels can be created using the HttpClientResponse.netSocket() method. In Eclipse Vert.x 4 this method has been updated.
To get a net socket for the connection of the request, send a socket handler in the request. The handler is called when the HTTP response header is received. The socket is ready for tunneling and can send and receive buffers.
The following example shows how to get net socket for a connection in Eclipse Vert.x 3.x releases.
The following example shows how to get net socket for a connection in Eclipse Vert.x 4.
4.6.2.3.4. New send() method in HttpClient class 复制链接链接已复制到粘贴板!
A new send() method is available in the HttpClient class.
The following code shows how to send a request in Eclipse Vert.x 4.
Future<HttpClientResponse> f1 = client.send(HttpMethod.GET, 8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"));
Future<HttpClientResponse> f1 = client.send(HttpMethod.GET, 8080, "localhost", "/uri", HttpHeaders.set("foo", "bar"));
In Eclipse Vert.x 4, HttpHeaders is an interface. In earlier releases of Eclipse Vert.x, HttpHeaders was a class.
The following new MultiMap methods have been added in the HttpHeaders interface. Use these methods to create MultiMap instances.
-
MultiMap.headers() -
MultiMap.set(CharSequence name, CharSequence value) -
MultiMap.set(String name, String value)
The following example shows how MultiMap instances were created in Eclipse Vert.x 3.x releases.
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
The following examples show how to create MultiMap instances in Eclipse Vert.x 4.
MultiMap headers = HttpHeaders.headers();
MultiMap headers = HttpHeaders.headers();
MultiMap headers = HttpHeaders.set("content-type", "application.data");
MultiMap headers = HttpHeaders.set("content-type", "application.data");
The CaseInsensitiveHeaders class is no longer public. Use the MultiMap.caseInsensitiveMultiMap() method to create a multi-map implementation with case insensitive keys.
The following example shows how CaseInsensitiveHeaders method was used in Eclipse Vert.x 3.x releases.
CaseInsensitiveHeaders headers = new CaseInsensitiveHeaders();
CaseInsensitiveHeaders headers = new CaseInsensitiveHeaders();
The following examples show how MultiMap method is used in Eclipse Vert.x 4.
MultiMap multiMap = MultiMap#caseInsensitiveMultiMap();
MultiMap multiMap = MultiMap#caseInsensitiveMultiMap();
OR
MultiMap headers = HttpHeaders.headers();
MultiMap headers = HttpHeaders.headers();
In earlier releases of Eclipse Vert.x, the version of HTTP running on a server was checked only if the application explicitly called the HttpServerRequest.version() method. If the HTTP version was HTTP/1.x, the method would return the 501 HTTP status, and close the connection.
From Eclipse Vert.x 4 onward, before a request is sent to the server, the HTTP version on the server is automatically checked by calling the HttpServerRequest.version() method. The method returns the HTTP version instead of throwing an exception when an invalid HTTP version is found.
4.6.2.3.8. New methods in request options 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the following new methods are available in the RequestOptions class:
- Header
- FollowRedirects
- Timeout
The following example shows how to use the new methods.
4.7. Changes in connection methods 复制链接链接已复制到粘贴板!
This section explains the changes in connection methods.
4.7.1. Checking if authentication is required for client 复制链接链接已复制到粘贴板!
The NetServerOptions.isClientAuthRequired() method has been removed. Use the getClientAuth() == ClientAuth.REQUIRED enumerated type to check if client authentication is required.
The following example shows how to use a switch statement to check if authentication of the client is required.
The following example shows how to use the check if authentication of the client is required in Eclipse Vert.x 4.
if (options.getClientAuth() == ClientAuth.REQUIRED) {
// behavior in releases prior to {VertX} {v4}
if (options.getClientAuth() == ClientAuth.REQUIRED) {
// behavior in releases prior to {VertX} {v4}
4.7.2. Upgrade SSL method uses asynchronous handler 复制链接链接已复制到粘贴板!
The NetSocket.upgradeToSsl() method has been updated to use Handler<AsyncResult> instead of Handler. The handler is used to check if the channel has been successfully upgraded to SSL or TLS.
4.8. Changes in logging 复制链接链接已复制到粘贴板!
This section explains the changes in logging.
4.8.1. Deprecated logging classes and methods 复制链接链接已复制到粘贴板!
The logging classes Logger and LoggerFactory along with their methods have been deprecated. These logging classes and methods will be removed in a future release.
4.8.2. Removed Log4j 1 logger 复制链接链接已复制到粘贴板!
The Log4j 1 logger is no longer available. However, if you want to use Log4j 1 logger, it is available with SLF4J.
4.9. Changes in Eclipse Vert.x Reactive Extensions (Rx) 复制链接链接已复制到粘贴板!
This section describes the changes in Reactive Extensions (Rx) in Eclipse Vert.x. Eclipse Vert.x uses the RxJava library.
4.9.1. Support for RxJava 3 复制链接链接已复制到粘贴板!
From Eclipse Vert.x 4.1.0, RxJava 3 is supported.
-
A new rxified API is available in the
io.vertx.rxjava3package. -
Integration with Eclipse Vert.x JUnit5 is provided by the
vertx-junit5-rx-java3binding.
To upgrade to RxJava 3, you must make the following changes:
-
In the
pom.xmlfile, under<dependency>change the RxJava 1 and 2 bindings fromvertx-rx-javaorvertx-rx-java2tovertx-rx-java3. -
In your application, update the imports from
io.vertx.reactivex.*toio.vertx.rxjava3.*. - In your application, update the imports for RxJava 3 types also. For more information, see What’s new section in RxJava 3 documentation.
4.9.2. Removed onComplete callback from write stream 复制链接链接已复制到粘贴板!
The WriteStreamSubscriber.onComplete() callback has been removed. This callback was invoked if WriteStream had pending streams of data to be written.
In Eclipse Vert.x 4, use the callbacks WriteStreamSubscriber.onWriteStreamEnd() and WriteStreamSubscriber.onWriteStreamError() instead. These callbacks are called after WriteStream.end() is complete.
WriteStreamSubscriber<Buffer> subscriber = writeStream.toSubscriber();
WriteStreamSubscriber<Buffer> subscriber = writeStream.toSubscriber();
The following example shows how to create the adapter from a WriteStream in Eclipse Vert.x 3.x releases.
subscriber.onComplete(() -> {
// Called after writeStream.end() is invoked, even if operation has not completed
});
subscriber.onComplete(() -> {
// Called after writeStream.end() is invoked, even if operation has not completed
});
The following examples show how to create the adapter from a WriteStream using the new callback methods in Eclipse Vert.x 4 release:
subscriber.onWriteStreamEnd(() -> {
// Called after writeStream.end() is invoked and completes successfully
});
subscriber.onWriteStreamEnd(() -> {
// Called after writeStream.end() is invoked and completes successfully
});
subscriber.onWriteStreamError(() -> {
// Called after writeStream.end() is invoked and fails
});
subscriber.onWriteStreamError(() -> {
// Called after writeStream.end() is invoked and fails
});
4.10. Changes in Eclipse Vert.x configuration 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x configuration.
4.10.1. New method to retrieve configuration 复制链接链接已复制到粘贴板!
The method ConfigRetriever.getConfigAsFuture() has been removed. Use the method retriever.getConfig() instead.
The following example shows how configuration was retrieved in Eclipse Vert.x 3.x releases.
Future<JsonObject> fut = ConfigRetriever. getConfigAsFuture(retriever);
Future<JsonObject> fut = ConfigRetriever. getConfigAsFuture(retriever);
The following example shows how to retrieve configuration in Eclipse Vert.x 4.
fut = retriever.getConfig();
fut = retriever.getConfig();
4.11. Changes in JSON 复制链接链接已复制到粘贴板!
This section describes changes in JSON.
4.11.1. Encapsulation of Jackson 复制链接链接已复制到粘贴板!
All the methods in the JSON class that implement Jackson types have been removed. Use the following methods instead:
| Removed Fields/Methods | New methods |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
For example, use the following code:
When using Jackson
TypeReference:In Eclipse Vert.x 3.x releases:
List<Foo> foo1 = Json.decodeValue(json, new TypeReference<List<Foo>>() {});List<Foo> foo1 = Json.decodeValue(json, new TypeReference<List<Foo>>() {});Copy to Clipboard Copied! Toggle word wrap Toggle overflow In Eclipse Vert.x 4 release:
List<Foo> foo2 = io.vertx.core.json.jackson.JacksonCodec.decodeValue(json, new TypeReference<List<Foo>>() {});List<Foo> foo2 = io.vertx.core.json.jackson.JacksonCodec.decodeValue(json, new TypeReference<List<Foo>>() {});Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Referencing an
ObjectMapper:In Eclipse Vert.x 3.x releases:
ObjectMapper mapper = Json.mapper;
ObjectMapper mapper = Json.mapper;Copy to Clipboard Copied! Toggle word wrap Toggle overflow In Eclipse Vert.x 4 release:
mapper = io.vertx.core.json.jackson.DatabindCodec.mapper();
mapper = io.vertx.core.json.jackson.DatabindCodec.mapper();Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Setting an
ObjectMapper:In Eclipse Vert.x 3.x releases:
Json.mapper = someMapper;
Json.mapper = someMapper;Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
From Eclipse Vert.x 4 onward, you cannot write a mapper instance. You should use your own static mapper or configure the
Databind.mapper()instance.
4.11.2. Object mapping 复制链接链接已复制到粘贴板!
In earlier releases, the Jackson core and Jackson databind dependencies were required at runtime.
From Eclipse Vert.x 4 onward, only the Jackson core dependency is required.
You will require the Jackson databind dependency only if you are object mapping JSON. In this case, you must explicitly add the dependency in your project descriptor in the com.fasterxml.jackson.core:jackson-databind jar.
The following methods are supported for the mentioned types.
Methods
-
JsonObject.mapFrom(Object) -
JsonObject.mapTo(Class) -
Json.decodeValue(Buffer, Class) -
Json.decodeValue(String, Class) -
Json.encode(Object) -
Json.encodePrettily(Object) -
Json.encodeToBuffer(Object)
-
Type
-
JsonObjectandJsonArray -
MapandList -
Number -
Boolean -
Enum -
byte[]andBuffer -
Instant
-
The following methods are supported only with Jackson bind:
-
JsonObject.mapTo(Object) -
JsonObject.mapFrom(Object)
The Eclipse Vert.x JSON types implement RFC-7493. In earlier releases of Eclipse Vert.x, the implementation incorrectly used Base64 encoder instead of Base64URL. This has been fixed in Eclipse Vert.x 4, and Base64URL encoder is used in the JSON types.
If you want to continue using the Base64 encoder in Eclipse Vert.x 4, you can use the configuration flag legacy. The following example shows how to set the configuration flag in Eclipse Vert.x 4.
java -Dvertx.json.base64=legacy ...
java -Dvertx.json.base64=legacy ...
During your migration from Eclipse Vert.x 3.x to Eclipse Vert.x 4 if you have partially migrated your applications, then you will have applications on both version 3 and 4. In such cases where you have two versions of Eclipse Vert.x you can use the following utility to convert the Base64 string to Base64URL.
You must use the utility methods in the following scenarios:
- Handling integration while migrating from Eclipse Vert.x 3.x releases to Eclipse Vert.x 4.
- Handling interoperability with other systems that use Base64 strings.
Use the following example code to convert a Base64URL to Base64 encoder.
String base64url = someJsonObject.getString("base64encodedElement")
String base64 = toBase64(base64url);
String base64url = someJsonObject.getString("base64encodedElement")
String base64 = toBase64(base64url);
The helper functions toBase64 and toBase64Url enable only JSON migrations. If you use object mapping to automatically map JSON objects to a Java POJO in your applications, then you must create a custom object mapper to convert the Base64 string to Base64URL.
The following example shows you how to create a object mapper with custom Base64 decoder.
The TrustOptions.toJSON method has been removed.
4.12. Changes in Eclipse Vert.x web 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x web.
In earlier releases of Eclipse Vert.x, you had to specify both the UserSessionHandler and SessionHandler handlers when working in a session.
To simplify the process, in Eclipse Vert.x 4, the UserSessionHandler class has been removed and its functionality has been added in the SessionHandler class. In Eclipse Vert.x 4, to work with sessions you must specify only one handler.
4.12.2. Removed the cookie interfaces 复制链接链接已复制到粘贴板!
The following cookie interfaces have been removed:
-
io.vertx.ext.web.Cookie -
io.vertx.ext.web.handler.CookieHandler
Use the io.vertx.core.http.Cookie interface instead.
4.12.3. Favicon and error handlers use Vertx file system 复制链接链接已复制到粘贴板!
The create methods in FaviconHandler and ErrorHandler have been updated. You must pass a Vertx instance object in the create methods. These methods access file system. Passing the Vertx object ensures consistent access to files using the 'Vertx' file system.
The following example shows how create methods were used in Eclipse Vert.x 3.x releases.
FaviconHandler.create(); ErrorHandler.create();
FaviconHandler.create();
ErrorHandler.create();
The following example shows how create methods should be used in Eclipse Vert.x 4.
FaviconHandler.create(vertx); ErrorHandler.create(vertx);
FaviconHandler.create(vertx);
ErrorHandler.create(vertx);
4.12.4. Accessing the template engine 复制链接链接已复制到粘贴板!
Use the method TemplateEngine.unwrap() to access the template engine. You can then apply customizations and configurations to the template.
The following methods that are used to get and set the engine configurations have been deprecated. Use the TemplateEngine.unwrap() method instead.
-
HandlebarsTemplateEngine.getHandlebars() -
HandlebarsTemplateEngine.getResolvers() -
HandlebarsTemplateEngine.setResolvers() -
JadeTemplateEngine.getJadeConfiguration() -
ThymeleafTemplateEngine.getThymeleafTemplateEngine() -
ThymeleafTemplateEngine.setMode()
4.12.5. Removed the locale interface 复制链接链接已复制到粘贴板!
The io.vertx.ext.web.Locale interface has been removed. Use the io.vertx.ext.web.LanguageHeader interface instead.
4.12.6. Removed the acceptable locales method 复制链接链接已复制到粘贴板!
The RoutingContext.acceptableLocales() method has been removed. Use the RoutingContext.acceptableLanguages() method instead.
4.12.7. Updated the method for mounting sub routers 复制链接链接已复制到粘贴板!
In earlier releases of Eclipse Vert.x, the Router.mountSubRouter() method incorrectly returned a Router. This has been fixed, and the method now returns a Route.
The JWTAuthHandler.create(JWTAuth authProvider, String skip) method has been removed. Use the JWTAuthHandler.create(JWTAuth authProvider) method instead.
The following example shows how JWT authentication handler was created in Eclipse Vert.x 3.x releases.
router // protect everything but "/excluded/path" .route().handler(JWTAuthHandler(jwtAuth, "/excluded/path")
router
// protect everything but "/excluded/path"
.route().handler(JWTAuthHandler(jwtAuth, "/excluded/path")
The following example shows how JWT authentication handler was created in Eclipse Vert.x 4.
router
.route("/excluded/path").handler(/* public access to "/excluded/path" */)
// protect everything
.route().handler(JWTAuthHandler(jwtAuth)
router
.route("/excluded/path").handler(/* public access to "/excluded/path" */)
// protect everything
.route().handler(JWTAuthHandler(jwtAuth)
In Eclipse Vert.x 4, OSGi environment is no longer supported. The StaticHandler.create(String, ClassLoader) method has been removed because the method was used in the OSGi environment.
If you have used this method in your applications, then in Eclipse Vert.x 4 you can either add the resources to the application classpath or serve resources from the file system.
4.12.10. Removed the bridge options class 复制链接链接已复制到粘贴板!
The sockjs.BridgeOptions class has been removed. Use the new sockjs.SockJSBridgeOptions class instead. The sockjs.SockJSBridgeOptions class contains all the options that are required to configure the event bus bridge.
There is no change in the behavior of the new class, except that the name of the data object class has changed.
In previous releases, when you used sockjs.BridgeOptions class to add new bridges, there were a lot of duplicate configurations. The new class contains all the possible common configurations, and removes duplicate configurations.
SockJSSocket no longer registers a clustered event bus consumer by default. If you want to write to the socket using the event bus, you must enable the writeHandler in SockJSHandlerOptions. When you enable the writeHandler, the event bus consumer is set to local by default.
You can configure the event bus consumer to a cluster.
SockJSHandlerOptions options = new SockJSHandlerOptions() .setRegisterWriteHandler(true) // enable the event bus consumer registration .setLocalWriteHandler(false) // register a clustered event bus consumer
SockJSHandlerOptions options = new SockJSHandlerOptions()
.setRegisterWriteHandler(true) // enable the event bus consumer registration
.setLocalWriteHandler(false) // register a clustered event bus consumer
4.12.12. New method for adding authentication provider 复制链接链接已复制到粘贴板!
The SessionHandler.setAuthProvider(AuthProvider) method has been deprecated. Use the SessionHandler.addAuthProvider() method instead. The new method allows an application to work with multiple authentication providers and link the session objects to these authentication providers.
From Eclipse Vert.x 4, OAuth2Auth.create(Vertx vertx) method requires vertx as a constructor argument. The vertx argument uses a secure non-blocking random number generator to generate nonce which ensures better security for applications.
4.13. Changes in Eclipse Vert.x Web GraphQL 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x Web GraphQL.
Eclipse Vert.x Web GraphQL is provided as Technology Preview only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs), might not be functionally complete, and Red Hat does not recommend to use them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
See Technology Preview Features Support Scope on the Red Hat Customer Portal for information about the support scope for Technology Preview features.
The following methods have been updated and are now supported on polyglot environments: * UploadScalar is now a factory, use the method UploadScalar.create() instead.
-
VertxBatchLoaderis now a factory, use the methodio.vertx.ext.web.handler.graphql.dataloader.VertxBatchLoader.create()instead. -
VertxDataFetcheris now a factory, use the methodio.vertx.ext.web.handler.graphql.schema.VertxDataFetcher.create()instead. -
VertxPropertyDataFetcheris now a factory, use the methodio.vertx.ext.web.handler.graphql.schema.VertxPropertyDataFetcher.create()instead.
In prior releases, the Eclipse Vert.x Web GraphQL handler could process its own POST requests. It did not need Eclipse Vert.x Web BodyHandler to process the requests. However, this implementation was susceptible to DDoS attacks.
From Eclipse Vert.x 4 onward, to process POST requests BodyHandler is required. You must install BodyHandler before installing Eclipse Vert.x Web GraphQL handler.
4.14. Changes in Micrometer metrics 复制链接链接已复制到粘贴板!
The following section describes the changes in Micrometer metrics.
In prior releases, the following metrics were recorded as distribution summaries for sockets. From Eclipse Vert.x 4 onward, these metrics are logged as counter, which report the amount of data exchanged.
Net client
-
vertx_net_client_bytes_read -
vertx_net_client_bytes_written
-
Net server
-
vertx_net_server_bytes_read -
vertx_net_server_bytes_written
-
For these counters, equivalent distribution summaries have been introduced for HTTP. These summaries are used to collect information about the request and response sizes.
HTTP client
-
vertx_http_client_request_bytes -
vertx_http_client_response_bytes
-
HTTP server
-
vertx_http_server_request_bytes -
vertx_http_server_response_bytes
-
4.14.2. Renamed the metrics 复制链接链接已复制到粘贴板!
The following metrics have been renamed.
| Old metrics name | New metrics name | Updated in components |
|---|---|---|
|
|
| Net client and server HTTP client and server |
|
|
| Datagram Net client and server HTTP client and server |
|
|
| Datagram Net client and server HTTP client and server |
|
|
| HTTP client HTTP server |
|
|
| HTTP client HTTP server |
|
|
| HTTP client HTTP server |
|
|
| HTTP client HTTP server |
|
|
| HTTP client HTTP server |
|
|
| |
|
|
| |
|
|
| |
|
|
| |
|
|
| |
|
|
| |
|
|
| |
|
|
| |
|
|
|
4.15. Changes in Eclipse Vert.x OpenAPI 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, a new module vertx-web-openapi is available. Use this module alone with vertx-web to develop contract-driven applications.
The new module works well with Eclipse Vert.x Web Router. The new module requires the following Eclipse Vert.x dependencies:
-
vertx-json-schema -
vertx-web-validation
The new module is available in the package io.vertx.ext.web.openapi.
In Eclipse Vert.x 4, the older OpenAPI module vertx-web-api-contract is supported to facilitate the migration to the new module. It is recommended that you move to the new module vertx-web-openapi to take advantage of the new functionality.
4.15.1. New module uses router builder 复制链接链接已复制到粘贴板!
The vertx-web-openapi module uses RouterBuilder to build the Eclipse Vert.x Web router. This router builder is similar to the router builer OpenAPI3RouterFactory in vertx-web-api-contract module.
To start working with the vertx-web-openapi module, instantiate the RouterBuilder.
You can also instantiate the RouterBuilder using futures.
The vertx-web-openapi module uses the Eclipse Vert.x file system APIs to load the files. Therefore, you do not have to specify / for the classpath resources. For example, you can specify petstore.yaml in your application. The RouterBuilder can identify the contract from your classpath resources.
4.15.2. New router builder methods 复制链接链接已复制到粘贴板!
In most cases, you can search and replace usages of old OpenAPI3RouterFactory methods with the new RouterBuilder methods. The following table lists a few examples of old and new methods.
Old OpenAPI3RouterFactory methods | New RouterBuilder methods |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Use the following syntax to access the parsed request parameters:
RequestParameters parameters = routingContext.get(io.vertx.ext.web.validation.ValidationHandler.REQUEST_CONTEXT_KEY);
int aParam = parameters.queryParameter("aParam").getInteger();
RequestParameters parameters = routingContext.get(io.vertx.ext.web.validation.ValidationHandler.REQUEST_CONTEXT_KEY);
int aParam = parameters.queryParameter("aParam").getInteger();
4.15.3. Handling security 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the methods RouterFactory.addSecurityHandler() and OpenAPI3RouterFactory.addSecuritySchemaScopeValidator() are no longer available.
Use the RouterBuilder.securityHandler() method instead. This method accepts io.vertx.ext.web.handler.AuthenticationHandler as an handler. The method automatically recognizes OAuth2Handler and sets up the security schema.
The new security handlers also implement the operations defined in the OpenAPI specification.
4.15.4. Handling common failures 复制链接链接已复制到粘贴板!
In vertx-web-openapi module, the following failure handlers are not available. You must set up failure handlers using the Router.errorHandler(int, Handler) method.
| Old methods in`vertx-web-api-contract` module | New methods in vertx-web-openapi module |
|---|---|
|
|
|
|
|
|
4.15.5. Accessing the OpenAPI contract model 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the OpenAPI contract is not mapped to plain old Java object (POJO). So, the additional swagger-parser dependency is no longer required. You can use the getters and resolvers to retrieve specific components of the contract.
The following example shows how to retrieve a specific component using a single operation.
JsonObject model = routerBuilder.operation("getPets").getOperationModel();
JsonObject model = routerBuilder.operation("getPets").getOperationModel();
The following example shows how to retrieve the full contract.
JsonObject contract = routerBuilder.getOpenAPI().getOpenAPI();
JsonObject contract = routerBuilder.getOpenAPI().getOpenAPI();
The following example shows you how to resolve parts of the contract.
JsonObject petModel = routerBuilder.getOpenAPI().getCached(JsonPointer.from("/components/schemas/Pet"));
JsonObject petModel = routerBuilder.getOpenAPI().getCached(JsonPointer.from("/components/schemas/Pet"));
4.15.6. Validating web requests without OpenAPI 复制链接链接已复制到粘贴板!
In the vertx-web-api-contract module, you could validate HTTP requests using HTTPRequestValidationHandler. You did not have to use OpenAPI for validations.
In Eclipse Vert.x 4, to validate HTTP requests use vertx-web-validation module. You can import this module and validate requests without using OpenAPI. Use ValidationHandler to validate requests.
4.15.7. Updates in the Eclipse Vert.x web API service 复制链接链接已复制到粘贴板!
The vertx-web-api-service module has been updated and can be used with the vertx-web-validation module. If you are working with vertx-web-openapi module, there is no change in the web service functionality.
However, if you do not use OpenAPI, then to use the web service module with vertx-web-validation module you must use the RouteToEBServiceHandler class.
The vertx-web-api-service module does not support vertx-web-api-contract. So, when you upgrade to Eclipse Vert.x 4, you must migrate your Eclipse Vert.x OpenAPI applications to vertx-web-openapi module.
Chapter 5. Changes in microservices patterns 复制链接链接已复制到粘贴板!
This section explains the changes in microservices patterns.
5.1. Changes in Eclipse Vert.x circuit breaker 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x circuit breaker.
The following methods have been removed from the CircuitBreaker class because they cannot be used with futures.
| Removed methods | Replacing methods |
|---|---|
|
|
|
|
|
|
5.2. Changes in Eclipse Vert.x service discovery 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x service discovery.
The following create methods in service discovery that have Handler<AmqpMessage> as an argument have been removed. These methods cannot be used with futures.
| Removed methods | Replacing methods |
|---|---|
|
|
|
|
|
|
The ServiceDiscovery.registerServiceImporter() and ServiceDiscovery.registerServiceExporter() methods are no longer fluent. The methods return Future<Void>.
The vertx-service-discovery-bridge-kubernetes adds the KubernetesServiceImporter discovery bridge. The bridge imports services from Kubernetes or Openshift into the Eclipse Vert.x service discovery.
From Eclipse Vert.x 4, this bridge is no longer registered automatically. Even if you have added the bridge in the classpath of your Maven project, it will not be automatically registered.
You must manually register the bridge after creating the ServiceDiscovery instance.
The following example shows you how to manually register the bridge.
JsonObject defaultConf = new JsonObject(); serviceDiscovery.registerServiceImporter(new KubernetesServiceImporter(), defaultConf);
JsonObject defaultConf = new JsonObject();
serviceDiscovery.registerServiceImporter(new KubernetesServiceImporter(), defaultConf);
The following sections describe the changes in Eclipse Vert.x authentication and authorization.
The Eclipse Vert.x authentication module has major updates in Eclipse Vert.x 4. The io.vertx.ext.auth.AuthProvider interface has been split into two new interfaces:
io.vertx.ext.auth.authentication.AuthenticationProviderImportantAuthentication feature is provided as Technology Preview only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs), might not be functionally complete, and Red Hat does not recommend to use them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
See Technology Preview Features Support Scope on the Red Hat Customer Portal for information about the support scope for Technology Preview features.
-
io.vertx.ext.auth.authorization.AuthorizationProvider
This update enables any provider to independently perform either authentication and authorization.
6.1. Migrating the authentication applications 复制链接链接已复制到粘贴板!
The authentication mechanism has changed at the result level. In earlier releases, the result was a User object, which was provider specific. In Eclipse Vert.x 4, the result is a common implementation of io.vertx.ext.auth.User.
The following example shows how a user was authenticated in Eclipse Vert.x 3.x releases.
The following example shows how to authenticate a user in Eclipse Vert.x 4.
6.2. Migrating the authorization applications 复制链接链接已复制到粘贴板!
Authorization is a new feature in Eclipse Vert.x 4. In earlier releases, you could only check if a user was authorized to perform the tasks on the User object. This meant that the provider was responsible for both authentication and authorization of the user.
In Eclipse Vert.x 4, the User object instances are not associated with a particular authentication provider. So you can authenticate and authorize a user using different providers. For example, you can authenticate a user using OAuth2 and perform authorization checks against MongoDB or SQL database.
The following example shows how an application checks if a user can use Printer #1234 in Eclipse Vert.x 3.x releases.
This authorization worked for JDBC and MongoDB. However it did not work for providers such as OAuth2, because the provider did not perform authorization checks. From Eclipse Vert.x 4, it is possible to perform such authorization checks by using different providers.
You can check authorizations on roles, permissions, logic operations, wildcards and any other implementation you add.
6.3. Changes in key management 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, there are major updates in handling keys. The most important change is that when a key loads, there is no distinction between public buffer and private buffer.
The following classes have been updated:
-
io.vertx.ext.auth.KeyStoreOptionsused to work withjcekeystores -
io.vertx.ext.auth.SecretOptionsused to handle symmetric secrets -
io.vertx.ext.auth.PubSecKeyOptionsused to handle public secret keys
The following section describes the changes in key management.
6.3.1. Secret options class is no longer available 复制链接链接已复制到粘贴板!
The SecretOptions class is no longer available. Use the new PubSecKeyOptions class instead to work with a cryptographic key.
The following example shows how methods of SecretOptions class were used in Eclipse Vert.x 3.x releases.
new SecretOptions()
.setType("HS256")
.setSecret("password")
new SecretOptions()
.setType("HS256")
.setSecret("password")
The following example shows how methods of PubSecKeyOptions class should be used in Eclipse Vert.x 4.
new PubSecKeyOptions()
.setAlgorithm("HS256")
.setSecretKey("password")
new PubSecKeyOptions()
.setAlgorithm("HS256")
.setSecretKey("password")
6.3.2. Updates in public secret keys management 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 3.x, the configuration object in public secret key management assumed that:
- Keys are configured as key-pairs.
- Key data is a PKCS8 encoded string without standard delimiters.
The following example shows how to configure key pair in Eclipse Vert.x 3.x.
In Eclipse Vert.x 4, you must specify both the public and private key.
The following example shows how to configure key pair in Eclipse Vert.x 4.
You can now handle X509 certificates using PubSecKeyOptions.
PubSecKeyOptions x509Certificate =
new PubSecKeyOptions()
// the buffer is the exact contents of the PEM file and had boundaries included in it
.setBuffer(x509PemString);
PubSecKeyOptions x509Certificate =
new PubSecKeyOptions()
// the buffer is the exact contents of the PEM file and had boundaries included in it
.setBuffer(x509PemString);
6.3.3. Changes in keystore management 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 3.x, KeyStoreOptions assumes that the keystore format is jceks, and the stored password is the same as the password of the key. As jceks is a proprietary format, it is recommended to use a standard format, such as JDK, instead.
When you use KeyStoreOptions in Eclipse Vert.x 4, you can specify a store type. For example, store types such as PKCS11, PKCS12, and so on can be set. The default store type is jceks.
In Eclipse Vert.x 3.x, all keystore entries would share the same password, that is, the keystore password. In Eclipse Vert.x 4, each keystore entry can have a dedicated password. If you do not want to set password for each keystore entry, you can configure the keystore password as the default password for all entries.
The following example shows how to load a jceks keystore in Eclipse Vert.x 3.x.
new KeyStoreOptions()
.setPath("path/to/keystore.jks")
.setPassword("keystore-password");
new KeyStoreOptions()
.setPath("path/to/keystore.jks")
.setPassword("keystore-password");
In Eclipse Vert.x 4, the default format is assumed to be the default format configured by JDK. The format is PKCS12 in Java 9 and above.
The following example shows how to load a jceks keystore in Eclipse Vert.x 4.
The following sections list methods deprecated and removed for authentication and authorization.
The following methods have been removed:
| Removed methods | Replacing methods |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
| No replacing method |
|
|
|
|
|
|
|
| No replacing method |
|
| No replacing method |
The following methods have been deprecated:
| Deprecated methods | Replacing methods |
|---|---|
|
|
|
|
|
|
|
| No replacing method |
|
|
|
|
| No replacing method |
The following classes have been deprecated:
| Deprecated class | Replacing class |
|---|---|
|
| Create user objects using the ` User.create(JsonObject)` method. |
|
| No replacing class |
|
|
|
|
| No replacing class |
|
|
|
|
|
Recommended to use |
|
| No replacing class |
Chapter 7. Changes in protocols 复制链接链接已复制到粘贴板!
This section explains the changes in networking protocols.
7.1. Changes in Eclipse Vert.x gRPC 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x gRPC.
7.1.1. New gRPC compiler plugin 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the module protoc-gen-grpc-java is no longer available. This module was a fork of the official gRPC compiler. In earlier releases of Eclipse Vert.x, you had to work with this fork. This fork is maintained by the Eclipse project. Working with the fork was complex.
In previous releases, to work with gRPC, the following details were added to pom.xml file.
In Eclipse Vert.x 4, a new gRPC compiler plugin is available. This plugin uses the official gRPC compiler instead of the fork. To work with the new gRPC plugin, add the following details to pom.xml file.
7.1.2. Migrating the generated code 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the new compiler is used. When the new gRPC plugin is used, the generated code is not written in the same source file. This is because the compiler does not allow custom code generation on its base class. The plugins must generate a new class with a different name to save the code.
In earlier releases of Eclipse Vert.x, the older gRPC plugin would write the generated code in the same source file.
For example, if you have the following descriptor:
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
In Eclipse Vert.x 3.x, the code would be generated in the GreeterGrpc class.
// 3.x
GreeterGrpc.GreeterVertxImplBase service =
new GreeterGrpc.GreeterVertxImplBase() {
...
}
// 3.x
GreeterGrpc.GreeterVertxImplBase service =
new GreeterGrpc.GreeterVertxImplBase() {
...
}
In Eclipse Vert.x 4, the code is generated in the VertxGreeterGrpc class.
// 4.x
VertxGreeterGrpc.GreeterVertxImplBase service =
new VertxGreeterGrpc.GreeterVertxImplBase() {
...
}
// 4.x
VertxGreeterGrpc.GreeterVertxImplBase service =
new VertxGreeterGrpc.GreeterVertxImplBase() {
...
}
7.1.3. gRPC APIs support futures 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the gRPC APIs support futures. The gRPC plugin generates promisified APIs. These APIs use the standard Eclipse Vert.x input and output arguments, which makes it easier to create standard Eclipse Vert.x applications.
The following example shows the use of promise in Eclipse Vert.x 3.x.
The following example shows the use of futures in Eclipse Vert.x 4.
7.2. Changes in Eclipse Vert.x MQTT 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x MQTT.
7.2.1. Some fluent methods in MQTT clients return future 复制链接链接已复制到粘贴板!
Some fluent methods in MqttClient class return Future instead of being fluent. For example, methods such as, MqttClient.connect(), MqttClient.disconnect(), MqttClient.publish() return future in Eclipse Vert.x 4.
The following example shows the use of publish() method in Eclipse Vert.x 3.x releases.
client
.publish("hello", Buffer.buffer("hello"), MqttQoS.EXACTLY_ONCE, false, false)
.publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);
client
.publish("hello", Buffer.buffer("hello"), MqttQoS.EXACTLY_ONCE, false, false)
.publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);
The following example shows the use of publish() method in Eclipse Vert.x 4 release.
client.publish("hello", Buffer.buffer("hello"), MqttQoS.EXACTLY_ONCE, false, false);
client.publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);
client.publish("hello", Buffer.buffer("hello"), MqttQoS.EXACTLY_ONCE, false, false);
client.publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);
7.2.2. MqttWill messages return buffer 复制链接链接已复制到粘贴板!
The MqttWill data object wraps a string message as an Eclipse Vert.x buffer instead of a byte array.
The following MQTT methods have been removed:
| Removed methods | Replacing methods |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7.3. Changes in Eclipse Vert.x Service Proxy 复制链接链接已复制到粘贴板!
The following section describes the changes in service proxy.
7.3.1. Using service proxy code generator 复制链接链接已复制到粘贴板!
The ServiceProxyProcessor class has been removed.
To use the service proxy code generator, you must import vertx-codegen with processor classifier in your classpath:
Service proxy reuses io.vertx.codegen.CodeGenProcessor from vertx-codegen to start the code generation of service proxy and handler.
Chapter 8. Changes in client components 复制链接链接已复制到粘贴板!
This section explains the changes in Eclipse Vert.x clients.
8.1. Changes in Eclipse Vert.x Kafka client 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x Kafka client.
8.1.1. AdminUtils Class is no longer available 复制链接链接已复制到粘贴板!
The AdminUtils class is no longer available. Use the new KafkaAdminClient class instead to perform administrative operations on a Kafka cluster.
8.1.2. Flush methods use asynchronous handler 复制链接链接已复制到粘贴板!
The flush methods in KafkaProducer class use Handler<AsyncResult<Void>> instead of Handler<Void>.
8.2. Changes in Eclipse Vert.x JDBC client 复制链接链接已复制到粘贴板!
From Eclipse Vert.x 4, the JDBC client supports SQL client. The SQL common module has also been merged in JDBC client, that is, io.vertx:vertx-sql-common merged in io.vertx:vertx-jdbc-client module. You will have to remove the io.vertx:vertx-sql-common dependency file because io.vertx:vertx-jdbc-client will include it. With the merging of SQL common client, all the database APIs have been consolidated into the JDBC client.
In Eclipse Vert.x 4, the SQL client has been updated to include the following clients:
- Reactive PostgreSQL client. In earlier releases, it included a reactive PostgreSQL client.
- Reactive MySQL client
- Reactive DB2 client
- Continues to include reactive PostgreSQL client. This client was available in Eclipse Vert.x 3.x releases as well.
- Existing JDBC client now includes both the JDBC client API and the SQL client API
The reactive implementations use the database network protocols. This makes them resource-efficient.
JDBC calls to database are blocking calls. The JDBC client uses worker threads to make these calls non-blocking.
The following section describes the changes in Eclipse Vert.x JDBC client.
8.2.1. Creating a pool 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, you can create a pool using the JDBC client APIs. In earlier releases, you could create only clients. You could not create pools.
The following example shows how to create a client in Eclipse Vert.x 3.x.
// 3.x SQLClient client = JDBCClient.create(vertx, jsonConfig);
// 3.x
SQLClient client = JDBCClient.create(vertx, jsonConfig);
The following example shows how to create a pool in Eclipse Vert.x 4.
// 4.x JDBCPool pool = JDBCPool.pool(vertx, jsonConfig);
// 4.x
JDBCPool pool = JDBCPool.pool(vertx, jsonConfig);
Though the Eclipse Vert.x 3.x APIs are supported in Eclipse Vert.x 4, it is recommended that you use the new JDBC client APIs in your applications.
A pool enables you to perform simple queries. You do not need to manage connections for simple queries. However, for complex queries or multiple queries, you must manage your connections.
The following example shows how to manage connections for queries in Eclipse Vert.x 3.x.
The following example shows how to manage connections for queries in Eclipse Vert.x 4.
8.2.2. Support for Typsesafe Config 复制链接链接已复制到粘贴板!
You can use jsonConfig for configurations. However, using the jsonConfig may sometimes result in errors. To avoid these errors, the JDBC client introduces Typesafe Config.
The following example shows the basic structure of a Typesafe Config.
To use Typesafe Config, you must include the agroal connection pool in your project. The pool does not expose many configuration options and makes the configuration easy to use.
8.2.3. Running SQL queries 复制链接链接已复制到粘贴板!
This section shows you how to run queries in the JDBC client.
8.2.3.1. Running one shot queries 复制链接链接已复制到粘贴板!
The following example shows how to run queries without managing the connection in Eclipse Vert.x 3.x.
The following example shows how to run queries without managing the connection in Eclipse Vert.x 4.
8.2.3.2. Running queries on managed connections 复制链接链接已复制到粘贴板!
The following example shows how to run queries on managed connections in Eclipse Vert.x 4.
8.2.4. Support for stored procedures 复制链接链接已复制到粘贴板!
Stored procedures are supported in the JDBC client.
The following example shows how to pass IN arguments in Eclipse Vert.x 3.x.
The following example shows how to pass IN arguments in Eclipse Vert.x 4.
In Eclipse Vert.x 3.x, the support for combining the IN and OUT arguments was very limited due to the available types. In Eclipse Vert.x 4, the pool is type safe and can handle the combination of IN and OUT arguments. You can also use INOUT parameters in your applications.
The following example shows handling of arguments in Eclipse Vert.x 3.x.
The following example shows handling of arguments in Eclipse Vert.x 4.
In the JDBC client, the data types have been updated.
-
For an argument of type
OUT, you can specify its return type. In the example, theOUTargument is specified as typeVARCHARwhich is a JDBC constant. - The types are not bound by JSON limitations. You can now use database specific types instead of text constants for the type name.
8.3. Changes in Eclipse Vert.x mail client 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x mail client.
8.3.1. MailAttachment is available as an interface 复制链接链接已复制到粘贴板!
From Eclipse Vert.x 4 onwards, MailAttachment is available as an interface. It enables you to use the mail attachment functionality in a stream. In earlier releases of Eclipse Vert.x, MailAttachment was available as a class and attachment for mails was represented as a data object.
MailConfig interface extends the NetClientOptions interface. Due to this extension, mail configuration also supports the proxy setting of the NetClient.
8.4. Changes in Eclipse Vert.x AMQP client 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x AMQP client.
The AMQP client methods that had Handler<AmqpMessage> as an argument have been removed. In earlier releases, you could set this handler on ReadStream<AmqpMessage>. However, if you migrate your applications to use futures, such methods cannot be used.
| Removed methods | Replacing methods |
|
|
|
|
|
|
|
|
|
8.5. Changes in Eclipse Vert.x MongoDB client 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x MongoDB client.
8.5.1. Methods removed from MongoDB client 复制链接链接已复制到粘贴板!
The following methods have been removed from MongoClient class.
| Removed methods | Replacing methods |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8.6. Changes in EventBus JavaScript client 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, the EventBus JavaScript client module is available in a new location. You will have to update your build systems to use the module from the new location.
In Eclipse Vert.x 3.x, the event bus JavaScript client was available in various locations, for example:
In Eclipse Vert.x 4, the JavaScript client is available only in npm. The EventBus JavaScript client module can be accessed from the following locations:
- CDN
Use the following code in your build scripts to access the module.
JSON scripts
{ "devDependencies": { "@vertx/eventbus-bridge-client.js": "1.0.0-1" } }{ "devDependencies": { "@vertx/eventbus-bridge-client.js": "1.0.0-1" } }Copy to Clipboard Copied! Toggle word wrap Toggle overflow XML scripts
<dependency> <groupId>org.webjars.npm</groupId> <artifactId>vertx__eventbus-bridge-client.js</artifactId> <version>1.0.0-1</version> </dependency><dependency> <groupId>org.webjars.npm</groupId> <artifactId>vertx__eventbus-bridge-client.js</artifactId> <version>1.0.0-1</version> </dependency>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.6.1. Versioning of JavaScript client 复制链接链接已复制到粘贴板!
Before Eclipse Vert.x 4, every Eclipse Vert.x release included a new release of the JavaScript client.
However, from Eclipse Vert.x 4 onward, a new version of JavaScript client will be available in npm only if there changes in the client. You do not need to update your client application for every Eclipse Vert.x release, unless there is a version change.
8.7. Changes in Eclipse Vert.x Redis client 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 4, use the Redis class to work with Redis client. The class RedisClient is no longer available.
- NOTE
-
To help you migrate your applications from
RedisClienttoRedisclass, a helper classRedisAPIis available.RedisAPIenables you to replicate the functionality similar toRedisClientclass.
The new class contains all the enhancements in protocols and Redis server features. Use the new class to:
- Work with all Redis commands
- Connect to single servers
- Connect to high availability servers where Redis Sentinel is enabled
- Connect to cluster configurations of Redis
- Execute requests in Redis extensions
- Communicate with both RESP2 and RESP3 server protocol servers
You can migrate your existing applications to new Redis client directly or use the helper class RedisAPI to migrate your applications in two steps.
Before migrating the applications you must create the client.
8.7.1.1. Creating the client 复制链接链接已复制到粘贴板!
The following example shows how a Redis client was created in Eclipse Vert.x 3.x releases.
// Create the redis client (3.x) RedisClient client = RedisClient .create(vertx, new RedisOptions().setHost(host));
// Create the redis client (3.x)
RedisClient client = RedisClient
.create(vertx, new RedisOptions().setHost(host));
The following example shows how to create a Redis client in Eclipse Vert.x 4.
// Create the redis client (4.x)
Redis client = Redis
.createClient(
vertx,
"redis://server.address:port");
// Create the redis client (4.x)
Redis client = Redis
.createClient(
vertx,
"redis://server.address:port");
In Eclipse Vert.x 4, the client uses the following standard connection string syntax:
redis[s]://[[user]:password@]server[:port]/[database]
redis[s]://[[user]:password@]server[:port]/[database]
8.7.1.2. Migrating applications to RedisAPI 复制链接链接已复制到粘贴板!
Using the 'RedisAPI` you can now decide how to manage the connection:
- You can let the client manage the connection for you using a pool.
Or
- You can control the connection by requesting a new connection. You must ensure to close or return the connection when done.
You must create the client and then update the applications to handle requests.
The following example shows how to handle requests after creating the client in Eclipse Vert.x 3.x releases.
The following example shows how to handle requests after creating the client in Eclipse Vert.x 4. The example uses a list for setting the key-value pairs instead of hard coding options. See Redis SET command for more information on arguments available for the command.
8.7.1.3. Migrating applications directly to Redis client 复制链接链接已复制到粘贴板!
When you migrate to the new Redis client directly:
- You can use all the new Redis commands.
- You can use extensions.
- You may reduce a few conversions from helper class to new client, which might improve the performance of your application.
You must create the client and then update the applications to handle requests.
The following example shows how to set and get requests after creating the client in Eclipse Vert.x 3.x releases.
The following example shows how to handle requests after creating the client in Eclipse Vert.x 4.
In Eclipse Vert.x 4, all the interactions use the send(Request) method.
8.7.1.4. Migrating responses 复制链接链接已复制到粘贴板!
In Eclipse Vert.x 3.x, the client used to hardcode all known commands till Redis 5, and the responses were also typed according to the command.
In the new client, the commands are not hardcoded. The responses are of the type Response. The new wire protocol has more range of types.
In older client, a response would be of following types:
-
null -
Long -
String -
JsonArray -
JsonObject(ForINFOandHMGETarray responses)
In the new client, the response is of following types:
-
null -
Response
The Response object has type converters. For example, converters such as:
-
toString() -
toInteger() -
toBoolean() -
toBuffer()
If the received data is not of the requested type, then the type converters convert it to the closet possible data type. When the conversion to a particular type is not possible, the UnsupportedOperationException is thrown. For example, conversion from String to List or Map is not possible.
You can also handle collections, because the Response object implements the Iterable interface.
The following example shows how to perform a MGET request.
8.7.2. Updates in Eclipse Vert.x Redis client 复制链接链接已复制到粘贴板!
This section describes changes in Redis client.
The deprecated term "slave" has been replaced with "replica" in Redis roles and node options.
- Roles
-
The following example shows the usage of
SLAVErole in Eclipse Vert.x 3.x releases.
The following example shows the usage of REPLICA role in Eclipse Vert.x 4.
- Node options
-
The following example shows you usage of node type
RedisSlavesin Eclipse Vert.x 3.x releases.
// Before (3.9) options.setUseSlaves(RedisSlaves);
// Before (3.9)
options.setUseSlaves(RedisSlaves);
The following example shows you usage of node type RedisReplicas in Eclipse Vert.x 4.
// After (4.x) options.setUseReplicas(RedisReplicas);
// After (4.x)
options.setUseReplicas(RedisReplicas);
Chapter 9. Changes in clustering 复制链接链接已复制到粘贴板!
This section explains the changes in clustering.
9.1. Clustered flag removed from options classes 复制链接链接已复制到粘贴板!
The methods and boolean value that were used to specify, get, and set clustering in Eclipse Vert.x applications have been removed from VertxOptions and EventBusOptions classes.
9.2. Changes in Infinispan cluster manager 复制链接链接已复制到粘贴板!
The following section describes the changes in the Infinispan cluster manager.
9.2.1. Updates in custom configurations 复制链接链接已复制到粘贴板!
The Infinispan cluster manager is based on Infinispan 12.
In Eclipse Vert.x 4, the clustering SPI has been redesigned. The subscription data model has changed. As a result of this, Eclipse Vert.x 3.x nodes and Eclipse Vert.x 4 nodes cannot be added together in the same Infinispan cluster.
The Eclipse Vert.x applications are not impacted by this change as the EventBus and SharedData APIs remain the same.
If you had a custom Infinispan configuration file in your Eclipse Vert.x 3.x application:
-
Change the
__vertx.subscache type to replicated instead of distributed. -
Add the replicated cache
__vertx.nodeInfo.
If you run an Eclipse Vert.x cluster on Openshift, the infinispan-cloud JAR is no longer needed. The JAR has been removed from the dependencies section of the build file. The configuration files that were bundled in this JAR are now included in the infinispan-core JAR.
9.3. Migrating clusters 复制链接链接已复制到粘贴板!
It is important to decide the migration strategy for your codebase. This is because you cannot add Eclipse Vert.x 3.x nodes and Eclipse Vert.x 4 nodes together in a single cluster for the following reasons:
- Cluster manager upgrades - Major version upgrades in cluster managers prevent backward compatibility.
- Subscription data changes - Eclipse Vert.x has changed the format of the EventBus subscription data stored in cluster managers.
- Transport protocol changes - Eclipse Vert.x has changed some fields in the message transport protocol in the cluster.
If you have an Eclipse Vert.x cluster for a single application or for some closely related microservices, you can migrate the entire codebase to the new cluster at one time.
However, if you cannot migrate the codebase at one time, use the recommendations in this section to migrate an Eclipse Vert.x 3.x codebase to Eclipse Vert.x 4.
9.3.1. Splitting the cluster 复制链接链接已复制到粘贴板!
If you have a cluster where different teams have deployed verticles for their applications, you can consider splitting the Eclipse Vert.x 3.x cluster into smaller ones. Note that after splitting the cluster, the separated components will not be able to communicate using the clustering features. You can split the cluster using the following components:
- EventBus request and reply - HTTP or RESTful web services, gRPC
-
EventBus send and publish - Messaging systems, Postgres
LISTENandNOTIFY, Redis Pub and Sub - Shared Data - Redis, Infinispan
After you split the cluster, each team can move to Eclipse Vert.x 4 when they are ready or if required.
9.3.2. Using Eclipse Vert.x EventBus Link 复制链接链接已复制到粘贴板!
If you cannot split your cluster, then use Vert.x EventBus Link to migrate your codebase incrementally.
Vert.x EventBus Link is a tool that connects an Eclipse Vert.x 3.x clustered EventBus to an Eclipse Vert.x 4 clustered EventBus.
The migration of shared data API, that is, maps, counters and locks is not supported.
The tool creates an EventBusLink object that implements the EventBus interface. An instance of EventBusLink is created on at least one node of each cluster. The instance is created by providing a set of addresses and its behavior depends on the message paradigm:
- fire and forget and request and reply - The message is sent to the remote cluster.
- publish - The message is sent to both this cluster and the remote cluster.
The Eclipse Vert.x EventBus Link creates a WebSocket server to receive messages and uses a WebSocket client to send them.
See the sections get started and using for more details.
Chapter 10. Miscellaneous changes in Eclipse Vert.x 复制链接链接已复制到粘贴板!
The following section describes miscellaneous changes in Eclipse Vert.x 4.
10.1. Removed the Starter class 复制链接链接已复制到粘贴板!
The Starter class has been removed. Use the Launcher class instead to start your Eclipse Vert.x applications without the main() method.
10.2. Isolated deployment for Java 8 复制链接链接已复制到粘贴板!
Eclipse Vert.x 4 supports Java 11. This Java version does not support isolated class loading. In Eclipse Vert.x 4, isolated class loading will be supported for Java 8.
10.3. Removed hook methods from Eclipse Vert.x context 复制链接链接已复制到粘贴板!
The methods Context.addCloseHook() and Context.removeCloseHook() methods have been removed from the Context class. These methods have been moved to the internal interface InternalContext.
10.4. Removed the clone methods from options 复制链接链接已复制到粘贴板!
The methods KeyCertOptions.clone(), TrustOptions.clone(), and SSLEngineOptions.clone() have been removed. Use the methods KeyCertOptions.copy(), TrustOptions.copy(), and SSLEngineOptions.copy() instead.
10.5. Removed equals and hashcode methods from options 复制链接链接已复制到粘贴板!
The VertxOptions.equals() and VertxOptions.hashCode() methods have been removed.
10.6. New method to check file caching 复制链接链接已复制到粘贴板!
The VertxOptions.fileResolverCachingEnabled() method has been removed. Use FileSystemOptions.isFileCachingEnabled() method instead to check if file caching has been enabled to resolve classpaths.
10.7. Service Provider Interface (SPI) metrics 复制链接链接已复制到粘贴板!
The Metrics.isEnabled() method has been removed. The Service Provider Interface (SPI) metrics will return a null object to indicate that metrics are not enabled.
10.8. Removed the pooled buffer methods 复制链接链接已复制到粘贴板!
The pooled buffer methods TCPSSLOptions.isUsePooledBuffers() and TCPSSLOptions.setUsePooledBuffers() have been removed.
10.10. Changes in Eclipse Vert.x JUnit5 复制链接链接已复制到粘贴板!
The following section describes the changes in Eclipse Vert.x JUnit5.
The vertx-core module has been updated to use a service provider interface for parameter injection. This change resulted in following updates in JUnit5:
-
You must call the
Vertxparameter before any parameter that requires it for creation. For example, when injecting aWebClient. -
vertx-junit5module supports only thevertx-coremodule. -
reactiverse-junit5-extensionsmodule hosts extensions that contain extra parameter types, such as,WebClient. RxJava 1 and 2 bindings are now available as
vertx-junit5-rx-javaandvertx-junit5-rx-java2modules in thevertx-junit5-extensionsrepository.From Eclipse Vert.x 4.1.0, the RxJava 3 binding
vertx-junit5-rx-java3is available.
The VertxTestContext.succeeding() and VertxTestContext.failing() methods have been deprecated. Use VertxTestContext.succeedingThenComplete() and VertxTestContext.failingThenComplete() methods instead.