您好,我是湘王,這是我的博客園,歡迎您來,歡迎您再來~
在前面的文章中已經把vert.x框架給跑起來了,但是實際開發中服務端是需要回應客戶端的請求的,所以肯定需要增加介面,但是該怎么加呢?有的人傾向于去搜索引擎找答案,其實還有一個比較好的方式是去官網看看有啥可以用的資料,比如說打開反應式編程的官網就能直接找到最新最準確的檔案:

可以看到,點擊進入【Vert.x Web】之后,再在左邊瀏覽,然后點擊【Routing by HTTP method】:

為了節約大家的時間,我就直接把代碼展示出來了,
先創建了介面路由和GET請求:
// 創建路由
Router router = Router.router(vertx);
// 創建一個GET請求
router.route(HttpMethod.GET, "/vertx/get")
.handler(context -> {
MultiMap queryParams = context.queryParams();
String username = queryParams.contains("username") ? queryParams.get("username") : "unknown";
String password = queryParams.contains("password") ? queryParams.get("password") : "unknown";
context.json(
new JsonObject()
.put("username", username)
.put("password", password)
);
});
再創建POST請求和HTTP服務
// 創建一個POST請求(用Postman測驗)
router.route(HttpMethod.POST, "/vertx/api/:id/:username/")
.handler(context -> {
String id = context.pathParam("id");
String username = context.pathParam("username");
System.out.println(id + " - " + username);
context.json(
new JsonObject()
.put("errcode", "200")
.put("message", "success")
);
});
// 創建HTTP服務
vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
if (http.succeeded()) {
startPromise.complete();
System.out.println("HTTP server started on port 8888");
} else {
startPromise.fail(http.cause());
}
});
現在可以先把代碼運行一下看看,比如在瀏覽中訪問
http://localhost:8080/vertx/get?username=xiangwang&password=123456
就能看到回傳的JSON資料:

然后在Postman中訪問POST請求,也能看到回傳的JSON資料

現在Web的功能已經演示完了,接下來再來看看資料庫的,同樣可以去官網 找檔案,可以看到,vertx支持大部分主流的SQL和NoSQL,

還是和之前一樣,為了節約大家的時間,我就直接把MySQL的演示代碼貼出來了,下面的配置是我電腦里面的MySQL資料庫連接:
// 創建MySQL連接
MySQLConnectOptions connectOptions = new MySQLConnectOptions()
// 埠號
.setPort(3306)
// IP地址或者域名
.setHost("192.168.227.100")
// 資料庫
.setDatabase("third")
// 用戶名
.setUser("root")
// 密碼
.setPassword("123456");
// 連接池選項
PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
// 創建連接池
MySQLPool client = MySQLPool.pool(vertx, connectOptions, poolOptions);
// 簡單查詢
client.query("SELECT * FROM apply_info")
.execute(ar -> {
if (ar.succeeded()) {
RowSet<Row> result = ar.result();
System.out.println("獲取到了 " + result.size() + " 行資料");
for (Row row : result) {
System.out.println("appid = " + row.getString("appid"));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
// 關閉
client.close();
});
有個小地方,如果提示報錯:

只需要把代碼中的【MySQLPool.pool(connectOptions, poolOptions);】改成【MySQLPool.pool(vertx, connectOptions, poolOptions);】就行了,
這就是最基礎的反應式編程的代碼示例了,雖然它還沒有大規模應用,但是管它呢,先卷起來再說,
感謝您的大駕光臨!咨詢技術、產品、運營和管理相關問題,請關注后留言,歡迎騷擾,不勝榮幸~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535130.html
標籤:Java
