当前位置:网站首页>Points needing attention in vertx programming
Points needing attention in vertx programming
2022-07-19 00:24:00 【forwardMyLife】
vertx Is based on netty Network programming development tools , If you want to use vertx To develop high-performance programs, we must be right netty Have a certain understanding of the underlying principle of ,netty It is an event driven network development framework , The bottom layer is based on JDK Of Nio Of socketChannle and Selector,io Multiplexing , The server is specially listening for connections EventLoop Threads , After the connection is established, create the corresponding SocketChannel, and io Event registration to work One of the thread pools EventLoop Thread bound Selector On , Every socketChannel There are corresponding channelPileline.channelPipeline Corresponding multiple channelHandler and ChannelContext, Handle read-write events in the form of a chain of responsibility .
1.verticle
Vert.x It provides a simple and convenient way out of the box 、 Extensible 、 similar Actor Model Deployment and concurrency model mechanism . You can use this model mechanism to keep your own code components .
This model is optional , It can also be based directly on vertxCore Create your application .
verticle Yes 3 class ,
| type | explain |
|---|---|
| Stardand Verticle | This is the most commonly used type Verticle —— They always run in Event Loop On the thread , Single verticle Bind one eventLoop Threads , An application can bind multiple vertcile example |
| Worker Verticle | This kind of Verticle Will run in Worker Pool On the thread in . An instance will never be executed by multiple threads at the same time |
| Multi-Threaded Worker Verticle | This kind of Verticle Will also run in Worker Pool On the thread in . An instance can be executed by multiple threads at the same time |
![]() |
The above is from vertx in action A Book
2.vertx Asynchronous callback programming
vertx In most cases, it runs in eventLoop On the thread , So the application must not have blocking code ,vertx Our world is completely asynchronous , This is a vertx The golden rule of ,
about http Requests or other middleware interactions , Use as much as possible vertx Realized api,
If in vertx Application initiation http request , Use as much as possible vertx Client provided , Use future or promise Get asynchronous results , In the callback , Processing results .
package com.ly;
import com.ly.entity.Good;
import com.ly.session.SessionEntity;
import io.vertx.core.*;
import io.vertx.core.http.*;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisOptions;
import io.vertx.redis.client.impl.RedisClient;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class VertxServer implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
VertxOptions vertxOptions = new VertxOptions();
vertxOptions.setMaxEventLoopExecuteTime(10000 * 60);
vertxOptions.setMaxEventLoopExecuteTimeUnit(TimeUnit.MILLISECONDS);
Vertx vertx = Vertx.vertx(vertxOptions);
HttpServerOptions options = new HttpServerOptions();
options.setIdleTimeout(3600);
options.setTcpKeepAlive(true);
HttpServer server = vertx.createHttpServer(options);
Router router = Router.router(vertx);
SessionStore sessionStore = SessionStore.create(vertx);
router.routeWithRegex("/static.*").handler(StaticHandler.create());
router.routeWithRegex(".*service.*")
.handler(SessionHandler.create(sessionStore)).handler(ctx -> {
if (ctx.request().path().contains("initSession")) {
ctx.request().response().setStatusCode(401)
.putHeader("Content-Type", "application/json").end((new JsonObject().put("msg", "illegal request").encode()));
} else {
ctx.next();
}
}).handler(ctx -> {
preCheck((result) -> {
if (result.succeeded()) {
doNext(ctx);
} else {
}
}, vertx);
}).failureHandler((ctx) -> {
System.out.println(ctx.failure());
});
server.requestHandler(router).listen(8081);
System.err.println("vertxServer start success");
}
}
public void preCheck(Handler<AsyncResult<Boolean>> asyncResultHandler, Vertx vertx) {
HttpClientOptions clientOptions = new HttpClientOptions();
HttpClient client = vertx.createHttpClient(clientOptions);
client.request(HttpMethod.POST, 8088, "localhost", "/hello1?name=ly").onSuccess(httpClientRequest -> {
httpClientRequest.headers().set("Content-Type", "application/json;charset=utf-8");
httpClientRequest.headers().set("Accept", "application/json;charset=utf-8");
httpClientRequest.end();
httpClientRequest.response().onSuccess(response -> {
response.bodyHandler(buffer -> {
String s = new String(buffer.getBytes(), StandardCharsets.UTF_8);
System.out.println("result:" + s);
asyncResultHandler.handle(Future.succeededFuture(Boolean.TRUE));
});
System.out.println(response.statusCode()+response.statusMessage());
});
});
}
private void doNext(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
Session session = ctx.session();
if (session.get("wow") == null) {
session.put("wow", "wow");
System.err.println((String) session.get("wow"));
ctx.request().remoteAddress();
List<Good> goodList = new ArrayList<>();
goodList.add(Good.builder().id(1).stockNumber(100).build());
session.put("goods", goodList);
} else {
System.out.println("goods:" + session.get("goods"));
}
SessionEntity sessionEntity = new SessionEntity();
sessionEntity.setId("28947208947");
session.put("typeTest", sessionEntity);
String path = ctx.request().path();
if (ctx.request().path().contains("service/removeCookie")) {
Cookie cookie = Cookie.cookie("vertx-web.session", new Date().getTime() + "");
cookie.setPath("/");
cookie.setSameSite(CookieSameSite.NONE);
ctx.addCookie(cookie);
ctx.request().response().addCookie(cookie);
} else if (path.contains("clearSession")) {
ctx.session().destroy();
}
response.putHeader("content-type", "text/plain");
response.end("hello word!");
}
}


After the response callback , Then decide whether to implement the corresponding results .
If you have to run blocking code, consider
1.context.runContext
2. about http applications , Use blockHandler The handler There will be work pool perform .
Official documents :
https://vertxchina.github.io/vertx-translation-chinese/core/Core.html
https://vertx.io/
边栏推荐
- Leetcode-7 integer inversion & leetcode 8 string conversion integer
- Using the third-party built-in module to realize the function of converting numbers to uppercase in nodejs
- Electron如何打包使其支持龙芯和方腾、兆芯平台的麒麟系统
- [Baidu PaddlePaddle] handwritten numeral recognition model deployment pad influence
- 开发到底要不要转行软件测试?一篇足以 最全方位分析
- Box model, table case
- How does electron package its Kirin system to support godson, fangteng and megacore platforms
- ES6之箭头函数
- 关于websocket的各种资料的收集
- Beautiful Soup模块是什么
猜你喜欢

TCP 糊涂窗口综合症(silly window syndrome)与 rate-based 流控

Four years after graduation, I changed three software testing jobs. Why am I still anxious?

vertx编程需注意的点

2022 latest Chinese Camtasia studio computer recording screen tool

毕业四年换了3份软件测试工作,我为何依然焦虑?

OpenCV DFT

With responsible AI | three certificates, aopeng China has also obtained ISO9001 and 27701 certification

php通过form表单上传Excel文件并把Excel数据导入到数据库中

What do LETV employees rely on to live a "fairy life" without a boss?

Mise en œuvre du modèle word2vec skip Gram
随机推荐
毕业四年换了3份软件测试工作,我为何依然焦虑?
推荐一个讲即时通信的博客
HMS core graphics and image technology shows the latest functions and application scenarios, and accelerates the construction of digital intelligence life
[examination] answer to the examination of class 2201 in stage II (no responsibility for mistakes)
The difference between cookies and session and JWT
Visionmaster communicates MODBUS with youao robot ur5e
Why is nodejs so fast?
Envoy lifecycle management
MySQL one basic syntax
Beautiful Soup模块是什么
WordPress主题分享:Avada主题v7.8.0免费下载 2022年最新版
关于websocket的各种资料的收集
Special instructions for PLC part of visionmaster multi process operation triggered by external PLC
大雪菜味题解--P4017 最大食物链计数
原子类及CAS
Openpose: estimation de la pose 2D Multi - personnes en temps réel à l'aide d'un champ d'affinité partiel
Leetcode-7 integer inversion & leetcode 8 string conversion integer
生成RedisTemplate的过程解读
2022-07-15 网工进阶(十九)BGP-状态机、对等体之间的交互原则、影响对等体关系建立的因素、对等体表、路由表、详细路由表、路由属性
Shell condition judgment exercise
