獲取當前Tomcat例項的埠

EthanSun發表於2019-01-19

有時需要在當前程式碼中獲取當前Server例項的埠號, 通過HttpServletRequest請求可以, 但有時也需要在沒有請求的情況下獲取到埠號.

用以下方法是可以獲取到的:

public int getHttpPort() {
    try {
        MBeanServer server;
        if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
            server = MBeanServerFactory.findMBeanServer(null).get(0);
        } else {
            log.error("no MBeanServer!");
            return -1;
        }

        Set names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

        Iterator iterator = names.iterator();
        if (iterator.hasNext()) {
            ObjectName name = (ObjectName) iterator.next();
            return Integer.parseInt(server.getAttribute(name, "port").toString());
        }
    } catch (Exception e) {
        log.error("getHttpPort", e);
    }
    return -1;
}

相關文章