vertx最简的入门例子-通知发送

背景
之前有个通知服务,用httpclient调用外部rest接口,但是总会由于外部的环境不可控,总会把消息堵住,或者延迟。
想起了vertx的异步处理,写了一个例子。只是简单的测试,并没有上生存。
测试结果,对以下几种情况vertx还是能够很好的应对的。
- 目标地址不存在,能够迅速返回失败
- 目标地址仅监听,不接受连接
- 目标地址能够连接,但不返回任何数据
- 目标能连接,但返回错误
maven 依赖
1 2 3 4 5
| <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web-client</artifactId> <version>4.4.3</version> </dependency>
|
Notifier
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions;
public class Notifier extends AbstractVerticle { @Override public void start() { HttpServer server = vertx.createHttpServer(); server.requestHandler(req -> { req.bodyHandler(buffer -> { String webhookUrl = req.getParam("target"); String signature = ""; WebClient client = WebClient.create(vertx, new WebClientOptions().setSsl(true)); client.get(443, webhookUrl, "/") .send() .onSuccess(r -> System.out.println("Received response" + " " + webhookUrl + " " + r.statusCode())) .onFailure(r -> System.out.println("error " + " " + webhookUrl + " " + r.getMessage())); req.response().end("ok"); }); }); server.listen(8000); } }
|
Bootstrap
1 2 3 4 5 6 7
| import io.vertx.core.Vertx; public class NotifierBootstrap { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); vertx.deployVerticle(Notifier.class.getName()); } }
|
测试的server
1 2 3 4 5 6 7 8 9 10
| import socket import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 443) sock.bind(server_address) sock.listen(1)
while True: print( 'waiting for a connection') connection, client_address = sock.accept()
|