Vert.x:如何延长特定路由或全局请求响应超时时间?
问题
我使用io.vertx.ext.web.openapi.RouterBuilder将OpenAPI规范的操作路由到EventBus:
RouterBuilder.create(vertx, openapiFile).onSuccess(routerBuilder -> { for (Operation operation : routerBuilder.operations()) operation.routeToEventBus(operation.getOperationId()); });
将其挂载到我的Router上:
router.route("/api/*").subRouter(routerBuilder.createRouter());
并创建工作verticle来消费消息并以ServiceResponse形式回复结果:
EventBus eb = vertx.eventBus(); eb.consumer("some_id", msg -> { msg.reply(ServiceResponse.completedWithPlainText(null).toJson()); });
部分操作耗时较长,我已通过以下配置延长工作verticle的执行时间:
new DeploymentOptions().setMaxWorkerExecuteTime(180_000).setMaxWorkerExecuteTimeUnit(TimeUnit.MILLISECONDS);
但路由上下文会在等待回复30000毫秒后超时,而工作verticle在超时后仍能正常工作。我尝试使用TimeoutHandler但未成功。请问如何全局或针对特定耗时路由延长超时时间?另外,Vert.x中默认的30000毫秒超时设置在哪里?
解决方案
1. 调整EventBus转发超时(单路由/全局)
你遇到的超时是RouterBuilder转发请求到EventBus后等待回复的超时,而非HTTP请求层面的超时,因此TimeoutHandler不生效。需要针对OpenAPI操作的EventBus转发逻辑设置超时:
- 单个操作定制:使用
routeToEventBus的重载方法,直接指定超时时间(单位毫秒):
// 给当前操作设置180秒的EventBus等待超时 operation.routeToEventBus(operation.getOperationId(), 180_000);
- 全局统一配置:遍历所有操作批量设置,或者通过
OpenAPIHandlerOptions全局定义:
// 方式1:遍历操作批量设置 RouterBuilder.create(vertx, openapiFile).onSuccess(routerBuilder -> { long globalTimeout = 180_000; for (Operation operation : routerBuilder.operations()) { operation.routeToEventBus(operation.getOperationId(), globalTimeout); } }); // 方式2:通过全局配置类设置 OpenAPIHandlerOptions handlerOptions = new OpenAPIHandlerOptions() .setEventBusTimeout(180_000); // 全局生效的EventBus等待超时 RouterBuilder.create(vertx, openapiFile, handlerOptions).onSuccess(routerBuilder -> { // 后续路由构建逻辑 });
2. 默认30000毫秒超时的来源
这个默认值是Vert.x Web OpenAPI组件中OpenAPIHandlerOptions类的eventBusTimeout字段默认配置,初始值即为30000毫秒(30秒)。
内容的提问来源于stack exchange,提问作者Lukas Weber
相关产品推荐
相关产品推荐

