无需HttpServletRequest获取WildFly上Spring应用的服务端及端口
不依赖HttpServletRequest获取WildFly服务器地址与端口的方案
针对你在Spring 3.4.0 + WildFly 34环境下的需求,这里提供几种不依赖HttpServletRequest的解决方案:
1. 读取WildFly内置系统属性
WildFly启动时会自动暴露一系列与绑定地址、端口相关的系统属性,直接读取这些属性即可:
jboss.bind.address:服务器绑定的IP地址jboss.http.port:HTTP服务端口jboss.https.port:HTTPS服务端口
代码示例:
public String getExternalWsUrl() { // 根据实际部署情况选择HTTP或HTTPS String scheme = "http"; // 读取系统属性,默认值为localhost/8080用于本地开发 String serverName = System.getProperty("jboss.bind.address", "localhost"); String serverPort = System.getProperty("jboss.http.port", "8080"); String serverUrl = scheme + "://" + serverName + ":" + serverPort; String wsFullPath = serverUrl + wsUrl; log.info("Calling WS path: {}", wsFullPath); return wsFullPath; }
这些属性的取值对应WildFly配置文件(standalone.xml或domain.xml)中的绑定设置,无需额外配置。
2. 通过Spring Environment读取配置
将服务器地址、端口配置到Spring配置文件中,结合WildFly的系统属性实现动态取值,同时支持多环境切换:
首先在application.properties中添加配置:
# 绑定WildFly系统属性,设置默认值 server.scheme=http server.bind.address=${jboss.bind.address:localhost} server.http.port=${jboss.http.port:8080}
然后在代码中注入Environment并读取:
private final Environment environment; private final WsService wsService; private final TaskService taskService; public ReportDestination(WsService wsService, TaskService taskService, Environment environment){ this.wsService = wsService; this.taskService = taskService; this.environment = environment; } public String getExternalWsUrl() { String scheme = environment.getProperty("server.scheme", "http"); String serverName = environment.getProperty("server.bind.address", "localhost"); String serverPort = environment.getProperty("server.http.port", "8080"); String serverUrl = scheme + "://" + serverName + ":" + serverPort; String wsFullPath = serverUrl + wsUrl; log.info("Calling WS path: {}", wsFullPath); return wsFullPath; }
3. 优先使用WildFly内部服务调用(推荐)
由于两个WAR部署在同一个WildFly实例中,完全不需要通过外部HTTP URL调用服务,直接通过内部机制引用对方服务更高效,也彻底规避了地址端口的依赖问题:
场景1:对方服务是Spring Bean
通过JNDI查找对方WAR中的Bean:
public ExternalWsService getExternalWsService() throws NamingException { InitialContext ctx = new InitialContext(); // JNDI格式:java:app/[对方WAR名称]/[Bean类名] return (ExternalWsService) ctx.lookup("java:app/other-war/ExternalWsService"); }
场景2:对方暴露JAX-WS服务
直接通过JNDI获取WebService端口实例,无需构建URL:
public ExternalWsPort getExternalWsPort() throws NamingException { InitialContext ctx = new InitialContext(); // 根据对方WS的配置查找端口JNDI return (ExternalWsPort) ctx.lookup("java:app/other-war/ExternalWsServicePort"); }
内容的提问来源于stack exchange,提问作者Salvatore Montagna
相关产品推荐
相关产品推荐

