Skip to content

Instantly share code, notes, and snippets.

@downgoon
Last active May 18, 2017 05:53
Show Gist options
  • Save downgoon/49eaf2e0b569818b624052d199895893 to your computer and use it in GitHub Desktop.
Save downgoon/49eaf2e0b569818b624052d199895893 to your computer and use it in GitHub Desktop.
import io.vertx.config.ConfigRetriever;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
public class HelloVerticle extends AbstractVerticle {
/* `http.port` can not be allowed in ` ~/.bash_profile` on Mac */
private static final String HTTP_PORT = "HTTP_PORT";
@Override
public void start(Future<Void> fut) throws Exception {
// Retrieve the port from the configuration,
// default to 8080.
// int configPort = config().getInteger(HTTP_PORT, 8080);
// System.out.println("configPort: " + configPort);
// int finalPort = retriever.getCachedConfig().getInteger(HTTP_PORT, 8080);
int finalPort = config().getInteger(HTTP_PORT, 8080);
System.out.println("finalPort: " + finalPort);
vertx.createHttpServer().requestHandler(r -> {
r.response().end("<h1>Hello World ! </h1>");
}).listen(finalPort, result -> {
if (result.succeeded()) {
fut.complete();
} else {
fut.fail(result.cause());
}
});
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
Verticle boxcloudVerticle = new HelloVerticle();
//
// vertx.deployVerticle(boxcloudVerticle);
// new JsonObject().put(HTTP_PORT, 10081)
DeploymentOptions options = new DeploymentOptions().setConfig(ConfigRetriever.create(vertx).getCachedConfig());
vertx.deployVerticle(boxcloudVerticle, options);
System.out.println("启动...");
}
}
@downgoon
Copy link
Author

@downgoon
Copy link
Author

一个是理解并发原理,然后是尽量把代码fluent化,这事就简单了

@downgoon
Copy link
Author

在这一点上,您可能会问自己:如何让多台服务器在同一主机和端口上侦听?尝试部署一个以上的实例时真的不会遇到端口冲突吗?

Vert.x在这里有一点魔法。

当您在与现有服务器相同的主机和端口上部署另一个服务器实例时,实际上它并不会尝试创建在同一主机/端口上侦听的新服务器实例。

相反,它内部仅仅维护一个服务器实例。当传入新的连接时,它以轮询的方式将其分发给任意一个连接处理器处理。

因此,Vert.x TCP 服务端可以水平扩展到多个核,并且每个实例保持单线程环境不变。

Vert.x在这里有一点魔法。

很重要的一点,verticle内部线程安全,很好滴利用起这个特性,你的代码会很漂亮

也很容易理解

handler内部是atomic,verticle内部线程安全,一般我们系统有几十个verticle很正常

你说的对于vertical的理解我是赞同的,我会直接把vertical理解成微服务中的单元,不管是基于tcp/http还是任何其他协议,也不管物理形态上这堆vertical到底在不在一起,最终就是服务的扩展,无论是性能还是业务

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment