WAR 파일을 JAR 파일로 다시 패키징

이 문서에서는 자바 8 애플리케이션을 자바 11/17 런타임에서 실행할 JAR 파일로 다시 패키징하는 방법을 설명합니다.

애플리케이션에는 PORT 환경 변수(일반적으로 8081)로 지정된 포트에서 HTTP 요청에 응답하는 웹 서버를 시작하는 Main 클래스가 있어야 합니다.

예를 들면 다음과 같습니다.

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration.ClassList;
import org.eclipse.jetty.webapp.WebAppContext;

/** Simple Jetty Main that can execute a WAR file when passed as an argument. */
public class Main {

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: need a relative path to the war file to execute");
      System.exit(1);
    }
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StrErrLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "INFO");

    // Create a basic Jetty server object that will listen on port defined by
    // the PORT environment variable when present, otherwise on 8080.
    int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
    Server server = new Server(port);

    // The WebAppContext is the interface to provide configuration for a web
    // application. In this example, the context path is being set to "/" so
    // it is suitable for serving root context requests.
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(args[0]);
    ClassList classlist = ClassList.setServerDefault(server);

    // Enable Annotation Scanning.
    classlist.addBefore(
        "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
        "org.eclipse.jetty.annotations.AnnotationConfiguration");

    // Set the the WebAppContext as the ContextHandler for the server.
    server.setHandler(webapp);

    // Start the server! By using the server.join() the server thread will
    // join with the current thread. See
    // "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()"
    // for more details.
    server.start();
    server.join();
  }
}

WAR 마이그레이션 예시

다음 안내에서는 자바 11/17 런타임에서 실행할 App Engine 자바 8 hello-world 애플리케이션을 JAR로 다시 패키징하는 방법을 보여줍니다.

마이그레이션은 appengine-simple-jetty-main 아티팩트를 사용합니다. 이는 WAR 파일을 로드하고 앱을 실행 가능한 JAR 파일로 패키징하는 간단한 Jetty 웹 서버가 포함된 Main 클래스를 제공합니다.

  1. 삽입된 Jetty 서버 아티팩트를 로컬 머신에 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples
    

    또는 ZIP 파일로 샘플을 다운로드하고 압축을 풉니다.

  2. 샘플 코드가 있는 디렉터리로 변경합니다.

    cd java-docs-samples/appengine-java11/appengine-simple-jetty-main/
    
  3. 종속 항목을 로컬로 설치합니다.

    mvn install
    
  4. 다음 코드를 pom.xml 파일에 추가합니다.

    • appengine-simple-jetty-main 종속 항목:
      <dependency>
        <groupId>com.example.appengine</groupId>
        <artifactId>simple-jetty-main</artifactId>
        <version>1</version>
        <scope>provided</scope>
      </dependency>
    • maven-dependency 플러그인:
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.6.1</version>
        <executions>
          <execution>
            <id>copy</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>
                ${project.build.directory}/appengine-staging
              </outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      App Engine은 ${build.directory}/appengine-staging 디렉터리에 있는 파일을 배포합니다. App Engine은 빌드에 maven-dependency 플러그인을 추가하여 지정된 종속 항목을 올바른 폴더에 설치합니다.
  5. app.yaml 파일에 entrypoint 요소를 만들어 appengine-simple-jetty-main 객체를 호출하고 WAR 파일을 인수로 전달합니다. WAR 버전은 pom.xml 파일에 나열된 버전과 동일해야 합니다.

    runtime: java
    env: flex
    runtime_config:
      operating_system: ubuntu18
      runtime_version: 11
    entrypoint: 'java -cp "*" com.example.appengine.jetty.Main helloworld-1.war'
    handlers:
    - url: /.*
      script: this field is required, but ignored
    
    manual_scaling:
      instances: 1
  6. 애플리케이션을 로컬에서 실행하려면 다음 안내를 따르세요.

    1. 애플리케이션을 패키징합니다.

      mvn clean package
      
    2. WAR 파일을 인수로 사용하여 서버를 시작합니다.

      예를 들어 java-docs-samples/appengine-java11/appengine-simple-jetty-main/ 폴더에서 다음 명령어를 실행하여 helloworld-war 샘플에서 서버를 시작할 수 있습니다.

      mvn exec:java -Dexec.args="../flexible/java-11/helloworld-war/target/helloworld-1.war"
      
    3. 웹브라우저에 다음 주소를 입력합니다.

      http://localhost:8080

  7. Maven 플러그인을 사용하여 애플리케이션을 배포하려면 다음 안내를 따르세요.

    mvn package appengine:deploy -Dapp.deploy.projectId=PROJECT_ID

    PROJECT_ID를 Google Cloud 프로젝트의 ID로 바꿉니다. pom.xml 파일에 이미 프로젝트 ID가 지정된 경우 실행할 명령어에 -Dapp.deploy.projectId 속성을 포함하지 않아도 됩니다.