개인적으로 사용 중이었던 방법인데 11번가도 동일하게 사용 중(참고 링크)

 

run_job.sh

#!/bin/bash

#apply env and etc
source ~/.bashrc


#사용 예
# ./run_job.sh 블라블라.jar 128M DB_HEALTH_CHECK argument_test=92

#실행할 Jar 심볼릭 링크 경로
JAR_LINK_PATH=$1

#Java 힙 메모리
JAVA_HEAP_MEMORY=$2

#Job name
JOB_NAME=$3

# 인자 갯수가 적은 경우 경고 메시지 출력
if [ $# -lt 3 ]; then
  echo "Usage: $0 JAR_LINK_PATH JAVA_HEAP_MEMORY JOB_NAME jobParameters[...]"
  exit 1
fi


#앞 3개 인자는 건너뜀
shift 3

jobParameters=""
for arg in "$@";
do
  if [ -n "$jobParameters" ]; then
    jobParameters+=" "
  fi
  jobParameters+="$arg"
done

JAVA_OPTS=" ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom"
JAVA_OPTS=" ${JAVA_OPTS} -server -Xms${JAVA_HEAP_MEMORY} -Xmx${JAVA_HEAP_MEMORY} -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${HOME}/oom_error_batch.hprof"

# 심볼릭 링크가 연결되어 있는 jar 파일 경로 가져오기
ORIGIN_JAR=$(readlink ${JAR_LINK_PATH})

echo "> ORIGIN_JAR_PATH: ${ORIGIN_JAR}"

$JAVA_HOME/bin/java -jar $JAVA_OPTS ${ORIGIN_JAR} --job.name=$JOB_NAME $jobParameters



switch-link.sh

#!/bin/bash

#사용 예
# ./switch-link.sh 블라블라/latest/블라블라_BATCH.jar

#실행할 Jar파일 전체 경로
DEPLOYED_JAR_FILE_FULL_PATH=$1

#실행할 Jar 파일 이름
JAR_FILE_NAME=$(basename "$DEPLOYED_JAR_FILE_FULL_PATH")

#APP 디렉토리 home
DEPLOYED_JAR_DIR=$(dirname "$DEPLOYED_JAR_FILE_FULL_PATH")
APP_HOME_PATH=$(dirname "$DEPLOYED_JAR_DIR")

#실행되는 app 심볼릭 링크가 위치할 디렉토리 경로
RUN_APP_LINK_DIR_PATH=${APP_HOME_PATH}

#run command로 전달된 argument 개수
ARG_CNT=$#

#run argument로 1개만 전달받아야함
REQUIRED_ARG_CNT=1

#기존에 배포된 디렉토리 유지할 개수(latest 디렉토리 제외한 deployed로 시작하는 디렉토리)
MAINTAIN_DEPLOYED_DIRECTORY_COUNT=10

function echo_host
{
        host=`hostname`
        echo "[$host] $1"
}

function check_arg
{

    if [ "$ARG_CNT" != "$REQUIRED_ARG_CNT" ] ; then
        echo_host "## Requested argument error. Required argument count is $REQUIRED_ARG_CNT. But requested $ARG_CNT"
        exit -1;
    fi

    # 배포된 파일이 존재하는지 확인
    if [ ! -f "$DEPLOYED_JAR_FILE_FULL_PATH" ]; then
        echo_host "Error: DEPLOYED_JAR_FILE_FULL_PATH does not exist."
        exit -1
    fi

}

#디렉토리 준비
function prepare_directory
{

    #실제 마지막 배포되어 실행될 jar파일의 심볼링 링크 디렉토리가 없다면 생성
    if [[ ! -e $RUN_APP_LINK_DIR_PATH ]]; then
        mkdir -p $RUN_APP_LINK_DIR_PATH
        echo_host ">>>> ${RUN_APP_LINK_DIR_PATH} (RUN_APP_LINK_DIR_PATH) Directory has been created."
    fi

}

# 마지막 배포된 jar파일을 해당 배포버전의 전용 디렉토리로 복사
function copy_deployed_jar_to_owned_dir {

    #마지막 배포된 Jar파일을 복사할 디렉토리 이름.
    # 참고: 오래된 디렉토리 삭제할 때 prefix deployed로 시작하는 디렉토리를 대상으로 하기 때문에 deployed라는 접두어는 유지해야함
    COPY_DIRECTORY_NAME=deployed-$(/bin/date +%Y-%m-%d_%H%M%S)

    # 배포되는 jar파일을 복사할 새로운 디렉토리 생성
    echo_host ">>>> mkdir deployed jar copy directory. [${APP_HOME_PATH}/${COPY_DIRECTORY_NAME}]"
    mkdir -p ${APP_HOME_PATH}/${COPY_DIRECTORY_NAME}


    # Deploy Path에 배포된 jar 파일을 새로운 디렉토리로 복사하기.
    echo_host ">>>> copy [${DEPLOYED_JAR_FILE_FULL_PATH}] to [${APP_HOME_PATH}/${COPY_DIRECTORY_NAME}/${JAR_FILE_NAME}]"
    cp -f ${DEPLOYED_JAR_FILE_FULL_PATH} ${APP_HOME_PATH}/${COPY_DIRECTORY_NAME}/${JAR_FILE_NAME}

}

#심볼릭 링크 생성(신규로 실행되는 배치 Job은 해당 심볼릭 링크를 바라봄으로 새로 배포된 jar로 실행되게 됨)
function create_run_jar_link {

    BEFORE_JAR_PATH=$(readlink ${RUN_APP_LINK_DIR_PATH}/${JAR_FILE_NAME})

    # 새로운 디렉토리 경로에 복사된 jar 파일로 링크 변경하기.
    # ln -Tfs TARGET LINK 명령으로 링크를 변경
    # -T option: –no-target-directory treat LINK_NAME as a normal file. 링크 파일을 일반 파일처럼 다루는 옵션
    # -f option: –force remove existing destination files. 심볼릭 링크가 이미 존재할 경우 덮어쓰는 옵션
    # -s option: –symbolic make symbolic links instead of hard links. 심볼릭 링크를 생성하는 옵션
    echo_host ">>>> Link switched from [$BEFORE_JAR_PATH] to [$APP_HOME_PATH/$COPY_DIRECTORY_NAME/$JAR_FILE_NAME]"
    ln -Tfs ${APP_HOME_PATH}/${COPY_DIRECTORY_NAME}/${JAR_FILE_NAME} ${RUN_APP_LINK_DIR_PATH}/${JAR_FILE_NAME}

}

function remove-old-directories() {

    # 1) 배포된 디렉토리 개수
    DIRECTORY_COUNT=$(ls -d ${APP_HOME_PATH}/deployed*/ | wc -l)

    # 유지할 디렉토리보다 많이 존재할 경우
    if [ $DIRECTORY_COUNT -gt $MAINTAIN_DEPLOYED_DIRECTORY_COUNT ]
    then

      # 2) 제거할 디렉토리 개수 카운트
      REMOVE_TARGET_COUNT=$(( ${DIRECTORY_COUNT} - ${MAINTAIN_DEPLOYED_DIRECTORY_COUNT}))

      # 3) 오래된 디렉토리부터 제거할 디렉토리 개수만큼 추출
      # 오래된 순으로 제거하기 위해 ls 명령어의 -t, -r 옵션 사용.
      # -t option: 파일과 디렉토리를 최근 시간 기준 내림차순 정렬
      # -r option: 정렬된 데이터의 순서를 오름차순으로
      REMOVE_TARGET_LIST=$(ls -dltr ${APP_HOME_PATH}/deployed*/ | head -$REMOVE_TARGET_COUNT | awk '{print $9}')

      # 삭제 대상 디렉토리 제거
      for file in ${REMOVE_TARGET_LIST}
      do
        echo ">>>> remove $file"
        /usr/bin/rm -rf ${file}
      done
    fi
}

# argument valid 체크
check_arg

#디렉토리 준비
prepare_directory

#jar 파일을 유지하기 위한 해당 jar용 디렉토리로 복사
copy_deployed_jar_to_owned_dir

#심볼릭 링크 생성
create_run_jar_link

#오래된 디렉토리 제거를 통해서 디스크 용량 관리
remove-old-directories

Keep connections warm and cheap

Network setup can cost 60–120 ms.
Reuse connections and cut TLS work.

Java 17 HttpClient:

var client = HttpClient.newBuilder()
    .version(HttpClient.Version.HTTP_2) // multiplex, fewer sockets
    .connectTimeout(Duration.ofMillis(200))
    .followRedirects(HttpClient.Redirect.NEVER)
    .sslParameters(new SSLParameters()) // allow session resumption
    .build();

// Example call; reuse client across requests
var req = HttpRequest.newBuilder(URI.create("https://api.internal/users/42"))
    .header("Connection", "keep-alive")
    .GET().build();
var res = client.send(req, HttpResponse.BodyHandlers.ofString());




HTTP/2 with keep-alive and TLS session resumption trimmed ~40–70 ms on coldish paths and stabilized p95.

Alternative: If the client sits behind a gateway, enable connection pools there and pin upstream IPs to tame DNS variance.



참고 - 상세 링크

좋은 글 참고 링크

 - 상세 사용 방법 등은 코드는 추후 해당 글에 추가 예정

spring boot 3.2 릴리즈 일정 확인 중에 알게된 링크

https://calendar.spring.io/

메모 목적으로 작성한 글이라서 생략된 부분이 많습니다.

 

  1.  목적/배경
    1. 현재 JDK 21의 VirtualThread기반으로 작업 중
    2. webflux를 이용해서 논블럭을 작성할 필요가 없어짐
      1. 유지보수, 읽기좋은 소스 등의 관점에서 기존 동기방식 스타일 코드 작성이 유리
      2. IO 블럭킹에 대한 성능 문제는 VirtualThread가 blocking 코드를 만나면 잠시 대기/큐잉 등 의 형태로 커버됨
    3. 다만, 통신용 모듈이 webclient로 기존에 작성되어 있음
      1. spring 디펜더시 문제 등의 이유로 23년 11월 23일에 spring boot 3.2가 릴리즈될때 rest client가 포함되서 해결 예정
      2. 지금 당장 webclient로 작성된 코드도 필요
    4. webclient를 block()으로 호출해서 임시 사용

 

------

샘플 소스

/**
 * Webclient로 외부 API를 호출
 *  - block()을 사용하여 결과를 받아옴
 *  - 500 에러가 발생하면 재시도
 *
 * @author 
 */
@Slf4j
public class WebClientBlockRetriveRequestSample {

  public static void main(String[] args) {

    final String reqUri = "http://localhost:87/delay/2"; //테스트 대상 URL
    final Duration timeoutDuration = Duration.ofSeconds(1); //Timeout

    String apiResponse = null;
    try {
      apiResponse = getRequestExcute(reqUri, timeoutDuration); //요청 실행
    } catch (BadWebClientRequestException e) {
      log.error("BadWebClientRequestException발생\n\n\t{}", e.getMessage(), e);
      throw e;
    } catch (WebClientTimeoutException te) {
      log.error("WebClientTimeoutException발생\n\n\t{}", te.getMessage(), te);
    }

    log.info("apiResponse: {}", apiResponse);

  }

  /**
   * 외부 HTTP 요청 실행
   *
   * @param reqUri
   * @param timeoutDuration
   * @return
   */
  public static String getRequestExcute(String reqUri, Duration timeoutDuration) {

    WebClient webClient = WebClient.builder()
        //.defaultHeader("Content-Type", "application/json")
        .build();

    String apiResponse = webClient.mutate().build().get()
        .uri(reqUri)
        .retrieve()
        .onStatus(httpStatus -> httpStatus.is4xxClientError() || httpStatus.is5xxServerError(),
            clientResponse -> handleErrorResponse(reqUri, clientResponse)
        ).bodyToMono(String.class)
        .timeout(timeoutDuration)
        .doOnError(throwable -> {

          if (throwable instanceof java.util.concurrent.TimeoutException) { //타임아웃 발생한 경우 핸들링을 위해서 예외 클래스 변경 처리
            log.error("TimeoutException: " + throwable.getMessage());
            throw new WebClientTimeoutException(String.format("Steam API no response whthin %s(millis)", timeoutDuration.toMillis()));
          }

        })
        .retryWhen(Retry.backoff(2, Duration.ofSeconds(2)).maxBackoff(Duration.ofSeconds(3)).jitter(0.5)
            .filter(throwable -> throwable instanceof WebClientNeedRetryException)) //특정 예외인 경우 재 시도
        .block(); //동기 방식으로 호출(virtual thread사용하기 때문에 문제 없음)

    return apiResponse;
  }


  public static Mono<? extends Throwable> handleErrorResponse(String uri, ClientResponse response) {

    if (response.statusCode().is4xxClientError()) {
      String errMsg = String.format("'%s' 4xx ERROR. statusCode: %s, response: %s, header: %s", uri, response.statusCode().value(), response.bodyToMono(String.class), response.headers().asHttpHeaders());
      log.error(errMsg);
      return Mono.error(new BadWebClientRequestException(response.statusCode().value(), errMsg));
    }

    if (response.statusCode().is5xxServerError()) { //5xx에러인 경우 재 시도 처리를 위해서 재 시도 필요 예외를 리턴
      String errMsg = String.format("'%s' 5xx ERROR. %s", uri, response.toString());
      log.error(errMsg);
      return Mono.error(new WebClientNeedRetryException(response.statusCode().value(), errMsg));
    }

    String errMsg = String.format("'%s' ERROR. statusCode: %s, response: %s, header: %s", uri, response.statusCode().value(), response.bodyToMono(String.class), response.headers().asHttpHeaders());
    log.error(errMsg);
    return Mono.error(new RuntimeException(errMsg));

  }

 

사용하는 커스텀 개발된 예외들

/**
 * 잘못된 파라미터로 요청시 발생하는 Exception
 *
 * @author 
 */
@Getter
public class BadWebClientRequestException extends RuntimeException {

  private static final long serialVersionUID = 2241080498857315158L;

  private final int statusCode;

  private String statusText;

  public BadWebClientRequestException(int statusCode) {
    super();
    this.statusCode = statusCode;
  }

  public BadWebClientRequestException(int statusCode, String msg) {
    super(msg);
    this.statusCode = statusCode;
  }

  public BadWebClientRequestException(int statusCode, String msg, String statusText) {
    super(msg);
    this.statusCode = statusCode;
    this.statusText = statusText;
  }
}

 

/**
 * Webclient로 호출 중 재 시도가 필요한 경우에 사용하는 Exception
 *
 * @author 
 */
@Getter
public class WebClientNeedRetryException extends RuntimeException {

  private static final long serialVersionUID = 3238789645114297396L;

  private final int statusCode;

  private String statusText;

  public WebClientNeedRetryException(int statusCode) {
    super();
    this.statusCode = statusCode;
  }

  public WebClientNeedRetryException(int statusCode, String msg) {
    super(msg);
    this.statusCode = statusCode;
  }

  public WebClientNeedRetryException(int statusCode, String msg, String statusText) {
    super(msg);
    this.statusCode = statusCode;
    this.statusText = statusText;
  }
#bash 쉘프롬프트 변경(필요시)
sudo su
echo 'PS1="[\u@\h \$PWD \D{%T}]\\$ "' >> /etc/bashrc && source /etc/bashrc


# Amazon Corretto JDK 21을 ~/apps 디렉토리 하위에 설치하는 명령어
# https://docs.aws.amazon.com/corretto/latest/corretto-21-ug/downloads-list.html 에서 다운로드 URL확이 ㄴ가능

# 디렉토리 생성(apps 디렉토리 하위에 생성 예정)
mkdir apps

# 다운로드
wget 'https://corretto.aws/downloads/latest/amazon-corretto-21-x64-linux-jdk.tar.gz' -O ~/apps/amazon-corretto-21-x64-linux-jdk.tar.gz


# 압축해제 및 삭제
cd ~/apps && tar -xzf amazon-corretto-21-x64-linux-jdk.tar.gz && rm -f amazon-corretto-21-x64-linux-jdk.tar.gz

# 심볼릭 링크 (필요시) 심볼릭 링크가 존재한다면, 삭제 후 재생성
cd ~/apps && rm jdk_21 && ln -s amazon-corretto-21.0.1.12.1-linux-x64 jdk_21

## DNS TTL 무제한 -> 10초로 수정 (어플리케이션마다 달라야 할 수 있음)
echo 'networkaddress.cache.ttl=10' >> ~/apps/jdk_21/conf/security/java.security

# 환경변수 및 디폴트 jdk 설정
echo 'export JAVA_21_HOME=~/apps/jdk_21' >> ~/.bashrc && echo 'export PATH=$JAVA_21_HOME/bin:$PATH' >> ~/.bashrc && source ~/.bashrc

# 기타 - jdk 버전 확인
$JAVA_HOME/bin/java -version
$JAVA_21_HOME/bin/java -version

메모 목적으로 생략한 내용이 많은 소스입니다.

 

  1. 목적/배경
    1. 구글 또는 애플 등의 스토어에 유저는 구매 후 스토어에 직접 취소할 수 있음
    2. 유저의 취소가 발생하면 개발자는 '권한'을 회수하거나 블럭 등을 해야함
      1. 유저 취소가 발생하면 실시간 알림도 이제는 받을 수 있음
      2. 아래 소스는 java로 간단히 작성한 과거 리스트를 조회하는 소스입니다.
  2. 소스
아래 구글 라이브러리 추가

<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-androidpublisher -->
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-androidpublisher</artifactId>
    <version>v3-rev20231012-2.0.0</version>
</dependency>

 

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.api.services.androidpublisher.model.VoidedPurchasesListResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collections;

/**
 * 구글 스토어에 유저가 구매 취소한 리스트를 조회하는 API 사용 샘플 소스
 * - Lists the purchases that were canceled, refunded or charged-back
 *
 * @author
 */
@Slf4j
public class GoogleVoidedpurchasesListSample {

    /**
     * API 호출할때의 어플리케이션 명. 자체 정의해서 사용
     */
    public static final String APPLICATION_NAME = "TEST-VoidedpurchasesListSample";

    /**
     * 테스트대상 구글앱의 패키지명
     */
    public static final String PACKAGE_NAME = "입력필요";

    /**
     * 인증을 위한 인증파일
     * - 프로토타이핑 중에 임시로 코드저장소외 외부환경 요소로 파일 저장 후 사용, 보안을 위해서 GIT과 같은 VCS에 올라가면 안되며, 라이브환경에서는 AWS Secrets Manager 등을 활용
     */
    public static final String AUTH_FILE_PATH = "인증용 json파일 경로. 구글 Cloud 콘솔에서 다운로드";

    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static HttpTransport HTTP_TRANSPORT;

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 실행 메소드
     * - 구글 API 정의서: https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.voidedpurchases/list?=en
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        final AndroidPublisher apiClient = getApiClient(AUTH_FILE_PATH, APPLICATION_NAME);


        AndroidPublisher.Purchases.Voidedpurchases.List listRequest = apiClient.purchases().voidedpurchases().list(PACKAGE_NAME);

        //추가 조회 필터링 조건들 설정
        listRequest.setMaxResults(2L);
        //listRequest.setToken("넥스트페이징 토큰");
        VoidedPurchasesListResponse voidedpurchasesList = listRequest.execute(); //실행

        //구글 응답 필드들 참고
        // 1) https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.voidedpurchases/list#response-body
        // 2) https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.voidedpurchases#VoidedPurchase
        log.info("voidedpurchasesList : {}", voidedpurchasesList);

        //응답 결과 중 voidedSource와 voidedReason 등을 참고해서 스토어 취소 악용한 유저에 대해서 블럭과 같은 이용제한 기능을 구현하면 됨


    }

    /**
     * 구글 인증 후 API를 바로 사용 가능한 클라이언트 객체를 리턴
     *
     * @param authFilePath
     * @param applicationName
     * @return
     * @throws IOException
     */
    public static AndroidPublisher getApiClient(String authFilePath, String applicationName) throws IOException {

        // Authorization.
        final Credential credential = authorizeWithServiceAccount(authFilePath);

        log.debug("credential : {}", credential);

        // Set up and return API client.
        return new AndroidPublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName).build();
    }

    /**
     * 구글 Android Publisher 인증
     *
     * @param apiAuthFilePath
     * @return
     * @throws IOException
     */
    public static Credential authorizeWithServiceAccount(String apiAuthFilePath)
            throws IOException {

        InputStream inputStream = new FileInputStream(apiAuthFilePath);

        GoogleCredential credential = GoogleCredential.fromStream(inputStream, HTTP_TRANSPORT,
                JSON_FACTORY);
        credential = credential.createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));

        return credential;
    }

}

JPA 사용 할 때 발생할 수 있는 N+1 문제와 관련해서 Spring Data JDBC에서 기능 추가를 준비하고 있나 봅니다.(2023년 8월 31일 글 업데이트 됨)
 - 참고. N+1문제)  교실과 학생이 1:N인 관계라면, 교실 10건을 조회하는 한번의 질의를 실행해도 학생 테이블은 교실 갯수 10번의 쿼리가 실행되어 총 11번 쿼리가 실행되는 문제
 
참고 링크
 - https://spring.io/blog/2023/08/31/this-is-the-beginning-of-the-end-of-the-n-1-problem-introducing-single-query
- https://github.com/spring-projects/spring-data-relational/issues/1445

+ Recent posts