首页 > 解决方案 > 在单个应用程序上运行 Spring Boot 服务器和 HttpServer?

问题描述

我有以控制器init开头的方法:HttpServer

public void init() {
    
        GatewayServer server = new GatewayServer("some_host", 8080);

        server.registerController(WorkshopOrderEndpoint.class);

        ControllerFactory.createController();

        server.startServer();
}

这是GatewayServer.class

public class GatewayServer {
    private static Logger logger = LogManager.getFormatterLogger(GatewayServer.class);

    private final String serverHost;

    private final String serverPort;

    private URI address;

    private ResourceConfig resourceConfig = null;

    private com.sun.net.httpserver.HttpServer server;

    public GatewayServer(final String host, final Integer port) {
        serverHost = host;
        serverPort = String.valueOf(port);

        try {
            logger.info("HTTP: Create Http-Server.");
            resourceConfig = new ResourceConfig();

            address = new URI(String.format("http://%s:%s/", serverHost, serverPort));

        } catch (URISyntaxException ex) {
            logger.error("HTTP: %s", ex.getMessage());
            LoggingHelper.sendExceptionLog(ex, "STATUS_URI_ERROR", "URI Encoding error.");
        } catch (ProcessingException ex) {
            logger.error("HTTP: %s", ex.getMessage());
            LoggingHelper.sendExceptionLog(ex, "STATUS_HTTP_ERROR", "HTTP-Server start error.");
        }

    }

    public void registerController(Class<?> controller) {
        if (resourceConfig != null) {
            logger.info("HTTP: Register Controller: %s", controller.getName());
            resourceConfig.register(controller);
        }
    }

    public void startServer() {
        server = JdkHttpServerFactory.createHttpServer(address, resourceConfig, false);
        logger.info("HTTP: Start Http-Server. Adress: %s", address);
        server.start();
    }

    public void stopServer(int delay) {
        logger.info("HTTP: Stop Http-Server. Address: %s", address);
        server.stop(delay);
    }
}

Eureka Server这是纯 java 应用程序,我想通过将此代码添加到方法中来启动 Spring Server 以便运行init()

 SpringRestApplication springRestApplication = new SpringRestApplication();
    springRestApplication.start();

SpringRestApplication.class在哪里启动 Spring Boot 服务器:

@SpringBootApplication
@EnableEurekaServer
public class SpringRestApplication {

    public void start() {
        
        SpringApplication.run(SpringRestApplication.class, new String[0]);
    }
}

我想在同一主机上运行两台服务器,但可以连接不同的端口Spring Boot Tomcat serverHttpServer

标签: javaspring-boot

解决方案


您可以在不同的端口上运行这两者。

Eugene 展示了几个更改 Spring Boot 应用程序端口的选项:https ://www.baeldung.com/spring-boot-change-port

这是最直接的:

public void start() {
    SpringApplication app = new SpringApplication(SpringRestApplication.class);
    app.setDefaultProperties(Collections
      .singletonMap("server.port", "8083"));
    app.run(args);
} 

推荐阅读