Restlight Server
esa.restlight.server.Restlite
为Restlight
架构中的Restlight Server
模块的入口类, 在ESA HttpServer
基础上丰富了更多的功能
- 引入业务线程池
- 基于
CompletableFuture
的响应式编程支持 - 线程调度
Filter
- 请求路由(根据url, method, header等条件将请求路由到对应的Handler)
This is the multi-page printable view of this section. Click here to print.
esa.restlight.server.Restlite
为Restlight
架构中的Restlight Server
模块的入口类, 在ESA HttpServer
基础上丰富了更多的功能
CompletableFuture
的响应式编程支持Filter
引入依赖
<dependency>
<groupId>io.esastack</groupId>
<artifactId>restlight-server</artifactId>
<version>${restlight.version}</version>
</dependency>
一行代码启动一个Http Server
Restlite.forServer()
.daemon(false)
.deployments()
.addRoute(route(get("/hello"))
.handle((request, response) ->
response.sendResult("Hello Restlight!".getBytes(StandardCharsets.UTF_8))))
.server()
.start();
运行并访问: http://localhost:8080/hello 即可看到输出:
Hello Restlight!
Mapping
表示一个请求匹配的条件, 用于确定一个请求是否能够路由到某个目标对对象。
eg.
curl -X GET http://localhost:8080/hello
Mapping.get("/hello");
curl -X POST http://localhost:8080/foo?a=1
Mapping.post("/foo")
.hasParam("a", "1");
curl -X GET -H "a:1" -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:8080/foo?a=1
Mapping.get("/foo")
.hasParam("a", "1")
.noneParam("b", "1")
.hasHeader("a", "1")
.noneHeader("b", "1")
.consumes(MediaType.APPLICATION_JSON)
.produces(MediaType.APPLICATION_JSON);
Route
Route
中包含了一个Mapping
用于路由匹配, 一个请求都将期望路由到具体的一个Route
, 如果找不到任何一个Route
则响应一个404
, 同时一个Route
还负责请求本身的业务处理。
eg.
Mapping mapping = Mapping.get("/foo");
Route route = Route.route(mapping)
.handle((request, response) -> {
response.sendResult("Hello Restlight!".getBytes(StandardCharsets.UTF_8));
})
.onError(((request, response, error) -> {
// error occurred
}))
.onComplete(((request, response, t) -> {
// request completed
}));
Mapping mapping = Mapping.get("/foo");
Route route = Route.route(mapping)
.handle((request, response) -> {
// biz logic here
response.sendResult("Hello Restlight!".getBytes(StandardCharsets.UTF_8));
});
Mapping mapping = Mapping.get("/foo");
Route route = Route.route(mapping)
.handle((request, response) -> {
// biz logic here
response.sendResult("Hello Restlight!".getBytes(StandardCharsets.UTF_8));
})
.onError(((request, response, error) -> {
// error occurred
}));
Mapping mapping = Mapping.get("/foo");
Route route = Route.route(mapping)
.handle((request, response) -> {
// biz logic here
response.sendResult("Hello Restlight!".getBytes(StandardCharsets.UTF_8));
})
.onComplete(((request, response, t) -> {
// request completed
}));
Route
请求处理生命周期均支持基于Completablefuture
的异步使用
Route route = route(get("/foo"))
.handleAsync((request, response) ->
CompletableFuture.runAsync(() -> {
// biz logic
}))
.onErrorAsync((request, response, throwable) ->
CompletableFuture.runAsync(() -> {
// error
}))
.onCompleteAsync((request, response, t) ->
CompletableFuture.runAsync(() -> {
// complete
}));