从 tomcat 获取服务器端口号,无需请求

是否有任何Tomcat API或配置可以告诉应用程序(可能是在启动时),它在哪个端口上运行而没有请求?

想象一下,有两个Web应用程序在同一个Tomcat中运行,其中一个需要从另一个调用Web服务。我们不希望请求离开Tomcat(如果您使用Apache服务器名称或绝对URL,请求将发出并再次返回,并且可以转到任何实例)并返回。为此,我知道机器的名称,但无法获得端口号。我知道我可以硬编码这些信息,但我不想这样做,因为我希望我的文件与应用程序服务器无关。war

我知道如果我们有一个HTTPServletRequest,我们可以找到它

这仅适用于Tomcat 6,不适用于Tomcat 7。


答案 1

有了这个:

List<String> getEndPoints() throws MalformedObjectNameException,
        NullPointerException, UnknownHostException, AttributeNotFoundException,
        InstanceNotFoundException, MBeanException, ReflectionException {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    QueryExp subQuery1 = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
    QueryExp subQuery2 = Query.anySubString(Query.attr("protocol"), Query.value("Http11"));
    QueryExp query = Query.or(subQuery1, subQuery2);
    Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), query);
    String hostname = InetAddress.getLocalHost().getHostName();
    InetAddress[] addresses = InetAddress.getAllByName(hostname);
    ArrayList<String> endPoints = new ArrayList<String>();
    for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
        ObjectName obj = i.next();
        String scheme = mbs.getAttribute(obj, "scheme").toString();
        String port = obj.getKeyProperty("port");
        for (InetAddress addr : addresses) {
            if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || 
                addr.isMulticastAddress()) {
                continue;
            }
            String host = addr.getHostAddress();
            String ep = scheme + "://" + host + ":" + port;
            endPoints.add(ep);
        }
    }
    return endPoints;
}

你会得到一个这样的列表:

[http://192.168.1.22:8080]

答案 2

对于任何对我们如何解决这个问题感兴趣的人,这里是模拟代码

Server server = ServerFactory.getServer();
        Service[] services = server.findServices();
        for (Service service : services) {
            for (Connector connector : service.findConnectors()) {
                ProtocolHandler protocolHandler = connector.getProtocolHandler();
                if (protocolHandler instanceof Http11Protocol
                    || protocolHandler instanceof Http11AprProtocol
                    || protocolHandler instanceof Http11NioProtocol) {
                    serverPort = connector.getPort();
                    System.out.println("HTTP Port: " + connector.getPort());
                }
            }


        }

推荐