내장 웹서버 응용 - 컨테이너와 포트
컨테이너와 포트
스프링 부트에서 기본적으로 Tomcat이 들어가있다. Tomcat을 사용하지 않고 jetty는 어떻게 설정하고 사용을 할까?
맨위에 스프링부트 도큐먼트를 보게 된다면 아래와같은 스프링부트 jetty사용 예시코드가 존재한다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- Exclude the Tomcat dependency -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Use Jetty instead -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
웹 서버 사용 안할 시
위 코드에서 웹서버를 추가하지 않거나,
application.properties에서
웹서버를 사용하지 않게 설정을 한다면(spring.main.web-application-type=none)
아래와같이 서버로나오지않고 어플리케이션으로 작동하게 될 것이다.
포트 수정
server.port=포트번호
랜덤으로 포트 사용할 거면
server.port=0
server.port = ${random.int} 이걸로 사용하면 안된다. 그 이유는 server.port=0으로 주는것은 사용가능한 포트중에 랜덤으로 주는 것이고, ${random.int} 는 말 그대로 랜덤값으로 주기 때문이다.
ApplicationListener<ServletWebServerInitializedEvent>
포트를 7070으로 바꾸었는데 이걸 확인할 수 있는 방법은 아래와 같다.
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class PortListner implements ApplicationListener<ServletWebServerInitializedEvent>{
/*
* ServletWebServerInitializedEvent는 웹서버가 호출이 될때 생성
*/
@Override
public void onApplicationEvent(ServletWebServerInitializedEvent servletwebserverinitializedevent) {
ServletWebServerApplicationContext applicationContext = servletwebserverinitializedevent.getApplicationContext();
System.out.println("=============================");
System.out.println("웹서버 포트 : " + applicationContext.getWebServer().getPort());
System.out.println("=============================");
}
}
ServletWebServerInitializedEvent은 웹서버가 생성이 된 후 발생되는 이벤트이다.
ServletWebServerInitializedEvent에서는 ServletWebServerApplicationContext를 꺼낸다.
Web Servet Application Server 이기 때문에 웹 서버를 알 수 있으며 포트까지 알 수가 있다.
ServletWebServerInitializedEvent가 WebServer가 생성이 된 후 생성되는 증거(?)