You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时获取OPS4J Pax Web/Apache Karaf动态分配的HTTP端口

如何在运行时获取OPS4J Pax Web动态分配的HTTP端口?

问题

希望在应用代码运行时,从OPS4J Pax Web中获取其动态分配的HTTP端口。

环境

使用自定义Apache Karaf 4.4.0发行版,已将http Karaf Feature设为启动特性安装。该http特性基于Jetty服务器,采用OPS4J Pax Web实现的Http Service Specification。已将配置文件org.ops4j.pax.web.cfg中的org.osgi.service.http.port属性设为0,让Pax Web自动选择HTTP端口,此功能正常工作。

已尝试的方法

尝试过多种方式读取运行时的HTTP端口,但均未成功:

  • 通过ConfigurationAdmin服务读取org.ops4j.pax.web.cfg中的org.osgi.service.http.port属性,得到的值为0;
  • 通过注入的HttpService(@Reference HttpService ...)无法获取端口,因为HttpService没有提供获取端口的方法;
  • 通过注入的Pax Web的WebContainer服务(@Reference WebContainer ...)也无法获取端口,因为WebContainer同样没有相关方法。

临时解决方案

为根Karaf容器的org.ops4j.pax.web.cfg配置文件设置固定的org.osgi.service.http.port值;对于子Karaf容器,注释该属性,通过一段代码片段选择HTTP端口并作为JVM参数传入,再通过InstanceService启动子容器,这样就能在应用代码中通过System.getProperty(...)读取该端口。但希望直接使用Pax Web自动选端口的功能,因此寻求运行时获取动态端口的方法。

最终解决方案

感谢Grzegorz Grzybek,通过以下代码片段成功获取动态分配的HTTP端口:

@Reference
private HttpServiceRuntime httpServiceRuntime;
...
Map<String, Object> properties = httpServiceRuntime.getRuntimeDTO().serviceDTO.properties;
String[] localHttpEndpoints = (String[]) properties.get(HttpServiceRuntimeConstants.HTTP_SERVICE_ENDPOINT);
URL localHttpEndpointUrl = new URL(localHttpEndpoints[0]);
int httpPort = localHttpEndpointUrl.getPort();

内容的提问来源于stack exchange,提问作者IProtex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:55:17