장 실습: 시도 기록과 아웃박스를 함께 남기기
게시글 등록에 시도 기록과 아웃박스를 붙이고, 실패한 등록과 성공한 등록에서 남는 행을 두 테스트로 확인합니다.
앞 글에서는 게시글과 성공 이벤트를 같은 트랜잭션에 넣었습니다. 이번에는 등록이 실패해도 시도했다는 기록은 남도록, 별도 트랜잭션을 쓰는 감사 기록까지 하나의 등록 흐름으로 모읍니다.
이 글을 읽고 나면 다음을 할 수 있습니다.
- 시도 기록을 남기는 빈과 게시글·아웃박스를 저장하는 빈을 연결합니다.
- 두 기록에 같은 전파 규칙을 썼을 때 사라지는 행을 테스트로 찾습니다.
- 실패한 등록과 성공한 등록에서 남아야 할 행 수를 확인합니다.
시작 상태
9장 첫 글에서 만든 jdbc-transaction-contracts 프로젝트를 11장까지 이어서 씁니다. 그 글의 build.gradle.kts에 Spring JDBC, 테스트 스타터, H2 의존성이 들어 있어야 합니다. 새 라이브러리를 설치할 필요는 없으며, 앞 글의 TransactionalOutboxAuditTest가 있는 상태에서 시작합니다. 이 파일은 그대로 두고 같은 패키지에 PostCreationWithAttemptAuditTest.java를 추가합니다.
명령은 프로젝트 루트에서 실행합니다. Windows PowerShell에서는 ./gradlew 대신 .\gradlew.bat을 씁니다. 테스트가 H2를 열므로 별도 데이터베이스 서버는 필요하지 않습니다.
완성 조건
- 표는
posts(id, title),outbox(event_id, aggregate_id, event_type),attempt_audit(request_id, outcome)셋입니다.request_id가attempt_audit의 기본 키입니다. AttemptAudit.record(String requestId)는attempt_audit에outcome이ATTEMPTED인 행을 넣습니다.AuditedPostCreation.create(requestId, postId, title, eventId, failBeforeCommit)은 시도를 기록하고,posts와outbox에 한 행씩 넣고,failBeforeCommit이true면 런타임 예외를 던집니다.- 실패한 등록 뒤에는
posts0행,outbox0행,attempt_audit1행입니다. - 성공한 등록 뒤에는 세 표 모두 1행입니다.
1단계: 시도 기록 없이 두 테스트 만들기
아래의 "완성 파일 전체"에서 설정과 표 생성, 두 테스트를 옮겨 파일의 골격을 만듭니다. 먼저 create의 attempts.record(requestId) 호출을 빼고, AttemptAudit.record에는 속성 없는 @Transactional을 둡니다. create의 두 INSERT와 failBeforeCommit에 따른 예외는 남겨 둡니다.
./gradlew test --tests board.tx.propagation.outbox.PostCreationWithAttemptAuditTest체크포인트: 두 테스트 모두 attempt_audit의 행 수를 확인하는 단언에서 실패합니다. 기대한 값은 1이고 실제는 0입니다. 게시글·아웃박스는 이미 성공 때 함께 남고 실패 때 함께 사라지지만, 시도 기록을 넣는 메서드를 아직 호출하지 않았습니다.
2단계: 다른 빈을 호출해도 함께 롤백되는지 보기
create의 첫 줄에 attempts.record(requestId)를 넣습니다. 시도 기록은 주입받은 별도 빈으로 호출하고, record의 애노테이션은 속성 없는 @Transactional 그대로 둡니다. 같은 명령으로 두 테스트를 다시 실행합니다.
체크포인트: 성공 테스트는 통과하지만 실패 테스트는 여전히 attempt_audit가 0행이어서 실패합니다. 별도 빈으로 나누었는데도 기록이 사라지는 이유를 전파 규칙의 REQUIRED와 연결해 설명해 보세요.
3단계: 시도 기록을 먼저 커밋하기
record의 전파를 Propagation.REQUIRES_NEW로 바꾸고 같은 테스트를 실행합니다. record에는 게시글 번호가 아니라 요청 ID만 넘깁니다. 앞선 글에서 본 것처럼 안쪽의 새 트랜잭션은 바깥이 아직 커밋하지 않은 새 행에 의존해서는 안 됩니다.
체크포인트: 두 테스트가 모두 통과합니다. 실패한 등록에는 시도만 남고, 성공한 등록에는 세 행이 함께 남습니다.
| 등록 결과 | posts | outbox | attempt_audit |
|---|---|---|---|
| 커밋 전 예외 | 0행 | 0행 | 1행 |
| 정상 완료 | 1행 | 1행 | 1행 |
record가 기본 전파 REQUIRED면 create가 시작한 트랜잭션에 참여합니다. 시도 기록의 INSERT는 게시글과 같은 연결에서 실행되고, create가 런타임 예외로 롤백될 때 함께 사라집니다. 다른 빈으로 나눠 프록시를 지나게 한 것만으로는 따로 커밋되지 않습니다. REQUIRES_NEW로 바꾸면 record는 새 연결에서 실행되어 create가 끝나기 전에 먼저 커밋되고, 뒤이은 롤백과 무관하게 남습니다.
다를 때 먼저 볼 곳
| 증상 | 확인할 곳 |
|---|---|
실패 테스트에서 attempt_audit가 0행 | record의 전파가 REQUIRES_NEW인지, create가 this가 아니라 주입받은 attempts로 호출하는지 |
실패 테스트에서 posts가 1행 | create에 @Transactional이 있는지, 예외가 RuntimeException의 하위 타입인지 |
성공 테스트에서 attempt_audit가 2행 | openContext가 표를 지우고 다시 만드는지 |
완성 파일 전체
PostCreationWithAttemptAuditTest.java 전체 보기
package board.tx.propagation.outbox;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
class PostCreationWithAttemptAuditTest {
private AnnotationConfigApplicationContext context;
private JdbcTemplate jdbc;
@BeforeEach
void openContext() {
context = new AnnotationConfigApplicationContext(Config.class);
jdbc = context.getBean(JdbcTemplate.class);
jdbc.execute("drop table if exists attempt_audit");
jdbc.execute("drop table if exists outbox");
jdbc.execute("drop table if exists posts");
jdbc.execute("create table posts(id bigint primary key, title varchar(120))");
jdbc.execute("create table outbox("
+ "event_id varchar(48) primary key, "
+ "aggregate_id bigint not null, "
+ "event_type varchar(48) not null)");
jdbc.execute("create table attempt_audit("
+ "request_id varchar(48) primary key, "
+ "outcome varchar(24) not null)");
}
@AfterEach
void closeContext() {
context.close();
}
@Test
void failedCreationLeavesOnlyTheAttempt() {
var creation = context.getBean(AuditedPostCreation.class);
assertThrows(
ExpectedBusinessFailure.class,
() -> creation.create(
"req-61", 61L, "failed", "evt-61", true));
assertEquals(0, count("posts"));
assertEquals(0, count("outbox"));
assertEquals(1, count("attempt_audit"));
}
@Test
void successfulCreationLeavesPostOutboxAndAttempt() {
context.getBean(AuditedPostCreation.class)
.create("req-62", 62L, "committed", "evt-62", false);
assertEquals(1, count("posts"));
assertEquals(1, count("outbox"));
assertEquals(1, count("attempt_audit"));
}
private int count(String table) {
return jdbc.queryForObject(
"select count(*) from " + table,
Integer.class);
}
public static class AttemptAudit {
private final JdbcTemplate jdbc;
AttemptAudit(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(String requestId) {
jdbc.update(
"insert into attempt_audit(request_id, outcome) "
+ "values (?, 'ATTEMPTED')",
requestId);
}
}
public static class AuditedPostCreation {
private final JdbcTemplate jdbc;
private final AttemptAudit attempts;
AuditedPostCreation(JdbcTemplate jdbc, AttemptAudit attempts) {
this.jdbc = jdbc;
this.attempts = attempts;
}
@Transactional
public void create(
String requestId,
long postId,
String title,
String eventId,
boolean failBeforeCommit
) {
attempts.record(requestId);
jdbc.update(
"insert into posts(id, title) values (?, ?)",
postId,
title);
jdbc.update(
"insert into outbox(event_id, aggregate_id, event_type) "
+ "values (?, ?, 'PostCreated')",
eventId,
postId);
if (failBeforeCommit) {
throw new ExpectedBusinessFailure();
}
}
}
static final class ExpectedBusinessFailure extends RuntimeException {
private static final long serialVersionUID = 1L;
}
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
static class Config {
@Bean
DataSource dataSource() {
var source = new JdbcDataSource();
source.setURL("jdbc:h2:mem:b92_outbox_attempt;DB_CLOSE_DELAY=-1");
return source;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
AttemptAudit attemptAudit(JdbcTemplate jdbc) {
return new AttemptAudit(jdbc);
}
@Bean
AuditedPostCreation auditedPostCreation(
JdbcTemplate jdbc,
AttemptAudit attempts
) {
return new AuditedPostCreation(jdbc, attempts);
}
}
}더 해 보기
완성한 과제에 스스로 기능을 붙여 보세요. 해설은 없고 방향만 적습니다.
- 같은
request_id로 두 번 요청하면 시도 기록의 INSERT가 기본 키 위반으로 실패합니다. 이때 게시글 등록은 계속되게 하세요. REQUIRES_NEW와 중첩 호출의 연습 문제 2번이 출발점입니다. - 감사 로그와 아웃박스의
OutboxRelay와AuditProjector를 이 과제의 설정에 옮겨, 성공한 등록의 이벤트를 두 번 전달해도 감사가 한 번만 남는지 확인하세요.
이것으로 11장을 마칩니다. 다음 장의 동시 요청과 공유 상태에서는 여러 요청이 같은 객체를 함께 쓸 때 생기는 문제와, 이 장에서 쓰기만 했던 프록시를 직접 만드는 방법을 다룹니다.