加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
README.adoc 20.91 KB
一键复制 编辑 原始数据 按行查看 历史
Julien Viet 提交于 2020-12-07 11:38 . Opentracing example

Vert.x core examples

Here you will find examples demonstrating Vert.x core in action.

Vert.x core provides fairly low level functionality for a diverse range of functions including HTTP, TCP, UDP, WebSockets, file system access, timers, verticles and more. Please consult the Vert.x core manual for detailed documentation on Vert.x core.

Examples can be run directly from the IDE by executing the main method. Alternatively, you can run them using the vertx command line tool (that need to be installed beforehand):

mvn clean compile
vertx run fully-qualified-name-of-the-example -cp target/classes

Adapt the -cp option value for your current working directory and operating system.

Dependencies required

To use Vert.x core in your own Maven or Gradle project add the following dependency

Group ID: io.vertx
Artifact ID: vertx-core

Embedding

Vert.x core can be embedded in any Java class and run that way if you like.

The Java embedded example shows an example of that. Just right click the class in your IDE to run it directly.

Net examples

These examples demonstrate usage of Vert.x net servers and clients - these are used for TCP (and SSL) servers and clients.

Echo

This example consists of an echo server verticle which serves TCP connections, and simply echoes back on the connection whatever it receives.

You can run the echo server then run telnet localhost 1234 from a console to connect to it. Type some stuff and see it echoed back to you.

It also contains an echo client, which creates a connection to the server, sends some data and logs out what it receives back. You can use that as an alternative to connecting via telnet.

Echo SSL

This is the same as the Echo example but using SSL to encrypt connections

HTTP examples

These examples demonstrate usage of HTTP with Vert.x.

Simple

A very simple HTTP server which always responds with the same response:

You can run the server then open a browser and point it at http://localhost:8080

And a simple HTTP client which makes a request to the server.

HTTPS

Like the simple example, but using HTTPS instead of HTTP

You can run the server then open a browser and point it at http://localhost:4443

And a simple HTTPS client which makes a request to the server.

Proxy connect

Connecting to a web server using an proxy. The proxy receives requests and connects to the endpoint server using a socket, then pass all the events between the client and the proxied server.

Proxy

A simple toy HTTP proxy. The proxy receives requests and forwards them to the endpoint server, it also takes responses from the other server and passes them back to the client.

Sendfile

This example demonstrates how you can serve static files from disk using a Vert.x http server.

You can run the server then open a browser and point it at http://localhost:8080

Note
In practice you would probably actually use Vert.x-Web for this rather than writing a web server at this low level. Serving files manually like this can leave you open to security exploits, e.g. by clients crafting URI paths which try to access resources outside of the permitted area. Vert.x-Web provides URI path normalisation to avoid these kinds of exploits and comes with a static file handler which also handles caching headers and other features that you would probably want when serving static files in a web application.

Simple form

This example demonstrates how you can handle an HTML form on the server.

You can run the server then open a browser and point it at http://localhost:8080

Note
In practice you would probably also use Vert.x-Web for this rather than writing a server at this low level. Vert.x-Web provides built in support for HTML forms, and avoids some of the security issues due to maliciously crafted URI paths.

Simple form file upload

This example demonstrates how you can handle file uploads from an HTML form submission.

You can run the server then open a browser and point it at http://localhost:8080

Note
In practice you would probably also use Vert.x-Web for this rather than writing a server at this low level. Vert.x-Web provides built in support for HTML forms and file uploads, and avoids some of the security issues due to maliciously crafted URI paths.

Http request body upload

This examples demonstrates an HTTP server receiving a request and pumping the request body to a file on disk without ever storing the entire request body fully in memory.

There’s also a client which sends a request to the server and pumps a file from disk to the HTTP request body. The file is uploaded successfully even if the file is very large (GigaBytes).

HTTP Server Sharing

A server that illustrates the round robin orchestrated by vert.x when several verticles are opening HTTP servers on the same port:

The GatewayVerticle deploys two instances of the HttpServerVerticle verticle.

You can run the server then open a browser and point it at http://localhost:8080. Requests will be handled by an instance after the other.

The Client illustrates the round robin by periodically requesting the server and displays the response content.

You can directly launch the HTTPServerVerticle using the vertx run command. Then you can set the number of instance you want:

vertx run io.vertx.example.core.http.sharing.HttpServerVerticle -instances 4

WebSockets echo example

This example shows a Vert.x HTTP server which handles websockets connections. This example simply echoes back to the client whatever it receives on the websocket.

There’s also a client which connects to the server, sends some data and logs out what it receives.

You can run the server then open a browser and point it at http://localhost:8080

Note
in practice you would probably use Vert.x-Web to build a web application that uses WebSockets

HTTP/2 examples

These examples demonstrate usage of HTTP/2 with Vert.x.

Simple

A very simple HTTP/2 server which always responds with the same response:

You can run the server then open a browser and point it at http://localhost:8080

And a simple HTTP/2 client which makes a request to the server.

Push

This example shows HTTP/2 push.

The server pushes script.js along with index.html:

You can run the server then open a browser and point it at http://localhost:8080

And a client sets a push handler to be notified of the incoming server side pushes:

H2C

Like the simple server but using clear text, also known as h2c, without TLS:

Note
this example won’t work with browsers are they don’t support h2c

Custom frames

HTTP/2 can be extended with custom frames, this example shows how to write and receive custom frames:

Event bus examples

These examples demonstrate usage of the event bus in Vert.x

Point to point

This example demonstrates point to point messaging between a receiver and a sender.

The receiver listens on an address on the event bus for incoming messages. When it receives a message it replies to it.

The sender sends a message to that address every second, when it receives a reply it logs it.

You can run the Java sender and receiver in your IDE or at the command line.

At the command line you should run Sender and Receiver in different consoles using the -cluster flag:

vertx run Receiver.java -cluster

vertx run Sender.java -cluster

The -cluster flag allows different Vert.x instances on the network to cluster the event bus together into a single event bus.

Publish / Subscribe

This example demonstrates publish / subscribe messaging between a receivers and a sender. With pub/sub messaging you can have multiple subscribers who all receive messages from publishers.

A receiver listens on an address on the event bus for incoming messages. When it receives a message it logs it.

The sender sends a message to that address every second, when it receives a reply it logs it.

You can start as many senders or receivers as you like in your IDE or at the command line.

At the command line you should run Sender and Receiver in different consoles using the -cluster flag:

vertx run Receiver.java -cluster

vertx run Sender.java -cluster

The -cluster flag allows different Vert.x instances on the network to cluster the event bus together into a single event bus.

MessageCodec

This example demonstrates how to write custom MessageCodec for send / publish / receive any type of object. It means you can send or receive custom data type objects directly through EventBus as well as primitive types like String.

In this example, there are two type of receivers. The first one is a local type which is deployed from sender, the other one is a cluster-wide type that launched from another instance of cluster. So you can see how MessageCodec works differently on the local EventBus and clustered EventBus.

You can start as many senders or receivers as you like in your IDE or at the command line.

At the command line you should run Sender and Receiver in different consoles using the -cluster flag:

vertx run ClusterReceiver.java -cluster

vertx run Sender.java -cluster

The -cluster flag allows different Vert.x instances on the network to cluster the event bus together into a single event bus.

SSL

This example demonstrates point to point messaging between a receiver and a sender with a transport level encryption.

The receiver listens on an address on the event bus for incoming messages. When it receives a message it replies to it.

The sender sends a message to that address every second, when it receives a reply it logs it.

You can run the Java sender and receiver in your IDE or at the command line.

At the command line you should run Sender and Receiver in different consoles using the -cluster flag:

vertx run Receiver.java -cluster

vertx run Sender.java -cluster

The -cluster flag allows different Vert.x instances on the network to cluster the event bus together into a single event bus. Depending of your configuration you may need to append to both command: ` -cp ../../../../../../../resources` in order to configure the cluster.

Future

Examples using Vert.x Futures are available in the Future directory.

Verticle examples

These examples show verticles being deployed and undeployed.

Deploy example

This example shows a verticle deploying another verticle in several different ways including:

  • Deploying without waiting for it to deploy

  • Deploying and waiting for it to deploy

  • Passing configuration to another verticle during deploy

  • Deploying more than one instance

  • Deploying as a worker verticle

  • Undeploying a verticle deployment explicitly

Polyglot Deploy example

This example shows a verticle deploying another language verticle that depends on a NPM module:

Asynchronous deployment example

This is similar to the deployment example, but it shows how the start and stop of a verticle can be asynchronous. This is useful if the verticle has some startup or cleanup to do that takes some time, and we wish to avoid blocking the an event loop.

Worker Verticle example

A simple example illustrating how worker verticle can be created and the thread switches when interacting with them. The worker verticle is not System.out.println(Thread.currentThread()); ed in the event loop and so can do blocking operations.

Execute blocking example

This example demonstrates how you can include blocking code in with your non blocking code in a way that doesn’t block an event loop:

Run the example then open a browser and point it at http://localhost:8080

Run the example then open a browser and point it at http://localhost:8080

High Availability

This example demonstrates the high availability feature of vert.x. When enabled, vert.x redeploys verticles to another node when the original node dies abruptly.

To run this example, you need to have a working cluster. Configure Hazelcast and append the required cluster-host to the commands if needed.

In your IDE:

  • Start the server by executing the main method of the GatewayVerticle class

  • Check that the http://localhost:8080 is served correctly

  • Start the bare instance by executing the main method of the BareInstance class

In a terminal, find the process related to the GatewayVerticle class execution and kill it using kill -9. The verticle is deployed on the bare instance. If you refresh the page, the message should be slightly different.

In command line:

To see the HA (high-availability) behavior you need three terminals.

First compile the project with mvn clean package

In the first terminal, go the the _core-examples` directory and launch:

vertx run io.vertx.example.core.ha.Server -ha -cp target/classes

Open a browser to http://localhost:8080. You should see something like:

Happily served by 97284@Macintosh.local

Be displayed id is OS and JVM specific, so you may have something completely different.

In the second terminal, go the the _core-examples` directory and launch:

vertx bare -cp target/classes/

In the third terminal, display the list of the Java process and kill the first one (smaller pid):

> jps | grep Launcher
97297 Launcher
97284 Launcher
> kill -9 97284

In your browser, refresh the page, you should see a different id such as:

Happily served by 97297@Macintosh.local

The verticle has been migrated.

Groovy verticles

Vert.x supports several formats to develop verticles in Groovy. This directory illustrates the different formats:

You can run these examples using the vertx command line. For example:

vertx run script.groovy

JSON streaming parser

A simple example illustrating how to use the streaming JsonParser to parse a giant array of small objects.

Custom ReadStream and WriteStream implementation

An example illustrating how to create your custom prefix length protocol to read and write objects in wire. The example uses Batch object, ReadStream and WriteStream implementation.

The protocol structure for Batch object is simple as illustrated below:

Length  : uInt32
Type    : byte ['O' for JsonObject | 'A' for JsonArray | 'B' for Buffer]
Payload : Buffer

The NetServer will receive the objects and write them back to the NetClient.

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化