Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JDBC 라이브러리 구현하기 - 4단계] 주노(최준호) 미션 제출합니다. #532

Merged
merged 7 commits into from
Oct 11, 2023
Merged
35 changes: 35 additions & 0 deletions app/src/main/java/com/techcourse/service/AppUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.techcourse.service;

import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;

public class AppUserService implements UserService {

private final UserDao userDao;
private final UserHistoryDao userHistoryDao;

public AppUserService(UserDao userDao, UserHistoryDao userHistoryDao) {
this.userDao = userDao;
this.userHistoryDao = userHistoryDao;
}

@Override
public User findById(long id) {
return userDao.findById(id);
}

@Override
public void insert(User user) {
userDao.insert(user);
}

@Override
public void changePassword(long id, String newPassword, String createBy) {
final var user = findById(id);
user.changePassword(newPassword);
userDao.update(user);
userHistoryDao.log(new UserHistory(user, createBy));
}
}
30 changes: 30 additions & 0 deletions app/src/main/java/com/techcourse/service/TxUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.techcourse.service;

import com.techcourse.domain.User;
import org.springframework.transaction.TransactionExecutor;

public class TxUserService implements UserService {

private final UserService userService;
private final TransactionExecutor transactionExecutor;

public TxUserService(UserService userService, TransactionExecutor transactionExecutor) {
this.userService = userService;
Comment on lines +11 to +12
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UserService 인터페이스로 받기 vs AppUserService 구현체로 받기

전자의 경우, 인자로 TxUserService가 들어오면 transactionExectuor의 메서드들이 여러 번 호출되는 문제가 생길 수 있을 것 같아요.

자주 발생할 경우 같지는 않아서 '굳이 그렇게 할 필요가 있나?'라는 고민도 드는데, 주노라면 어떤 선택을 하실건가요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 굳이 그렇게 할 필요가 있나?라는 입장으로 이정도는 개발자의 책임의 영역이라고 생각해도 무관할 것 같습니다 😅

Copy link

@0chil 0chil Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 동의합니다.
라이브러리를 개발하는 입장에서
타입을 특정 구현체로 제한시켜 유연성을 희생하기보다는, 이 정도는 사용자 책임으로 남기는 것이 좋을 것 같아요.

어떤 사용자는 정말 TxUserService를 중첩해서 만들고 싶을 수도 있죠!

좋은 답변 감사합니다!

this.transactionExecutor = transactionExecutor;
}

@Override
public User findById(long id) {
return transactionExecutor.executeWithResult(() -> userService.findById(id));
}

@Override
public void insert(User user) {
transactionExecutor.execute(() -> userService.insert(user));
}

@Override
public void changePassword(final long id, final String newPassword, final String createBy) {
transactionExecutor.execute(() -> userService.changePassword(id, newPassword, createBy));
}
}
36 changes: 4 additions & 32 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
package com.techcourse.service;

import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;
import org.springframework.transaction.TransactionExecutor;
import org.springframework.transaction.TransactionManager;

public class UserService {
public interface UserService {

private final UserDao userDao;
private final UserHistoryDao userHistoryDao;
private final TransactionManager transactionManager;

public UserService(final TransactionManager transactionManager, final UserDao userDao, final UserHistoryDao userHistoryDao) {
this.userDao = userDao;
this.userHistoryDao = userHistoryDao;
this.transactionManager = transactionManager;
}

public User findById(final long id) {
return userDao.findById(id);
}

public void insert(final User user) {
userDao.insert(user);
}

public void changePassword(final long id, final String newPassword, final String createBy) {
TransactionExecutor.execute(transactionManager, () -> {
final var user = findById(id);
user.changePassword(newPassword);
userDao.update(transactionManager.getConnection(), user);
userHistoryDao.log(transactionManager.getConnection(), new UserHistory(user, createBy));
});
}
User findById(final long id);
void insert(final User user);
void changePassword(final long id, final String newPassword, final String createBy);
}
8 changes: 4 additions & 4 deletions app/src/test/java/com/techcourse/service/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionExecutor;
import org.springframework.transaction.TransactionManager;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -34,7 +35,7 @@ void setUp() {
@Test
void testChangePassword() {
final var userHistoryDao = new UserHistoryDao(jdbcTemplate);
final var userService = new UserService(transactionManager, userDao, userHistoryDao);
final var userService = new AppUserService(userDao, userHistoryDao);

final var newPassword = "qqqqq";
final var createBy = "gugu";
Expand All @@ -47,13 +48,12 @@ void testChangePassword() {

@Test
void testTransactionRollback() {
// 트랜잭션 롤백 테스트를 위해 mock으로 교체
final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate);
final var userService = new UserService(transactionManager, userDao, userHistoryDao);
final var appUserService = new AppUserService(userDao, userHistoryDao);
final var userService = new TxUserService(appUserService, new TransactionExecutor(transactionManager));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 테스트를 돌려보시면 예외가 발생할 거에요!
JdbcTemplate:51의 try-with-resources 에 의해 이미 Connection 객체가 닫혔기 때문인데요,
어떻게 해결하면 좋을까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JdbcTemplate의 Connection을 DatasourceUtils를 이용하여 가져오도록 수정했습니다. 이 과정에서 try-with-resource의 대상에서 제외시켰습니다.

추가로 Transaction 수행 과정에서 TransactionManager가 Connection을 필드로 가짐으로써 close된 Connection이 계속 남아있던 부분을 확인했습니다.
Transaction begin 시 Connection이 close되어있다면 connection을 새롭게 갱신하는 로직을 추가했습니다.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JdbcTemplate의 Connection을 DatasourceUtils를 이용하여 가져오도록 수정했습니다. 이 과정에서 try-with-resource의 대상에서 제외시켰습니다.

확인했습니다. 이제 DataSourceUtils 가 커넥션을 열고 닫는 책임을 가지겠네요.

추가로 Transaction 수행 과정에서 TransactionManager가 Connection을 필드로 가짐으로써 close된 Connection이 계속 남아있던 부분을 확인했습니다.
Transaction begin 시 Connection이 close되어있다면 connection을 새롭게 갱신하는 로직을 추가했습니다.

고생하셨습니다~! 이제 닫힌 커넥션을 갱신할 수 있게 되었네요!

하지만 이 방법은 임시방편이라는 생각이 들어요.
TransactionManager의 인스턴스를 정말 하나만 만들어도 될까요?
저는 주노 코드에서 TransactionManager 객체와 '논리적 트랜잭션' 이라고 부르는 그것이 생명 주기를 같이 한다고 느껴집니다.
그래서 현재 상태로는 여러 쓰레드가 하나의 논리적 트랜잭션을 사용하는 꼴이 되므로 멀티쓰레드 환경을 지원하지 못할 것이라는 의심이 들어요.

멀티 쓰레드 환경으로 가면,
여러 쓰레드가 Service 객체 -> TransactionExecutor 객체 -> TransactionManager 객체를 공유해 사용할 거에요.
( -> 는 객체 참조입니다!)

정말 그렇게 되어도 괜찮을까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 멀티스레드 환경 생각도 못하고있었네요...!!!
날카로운 지적 감사합니다 🙇‍♂️🙇‍♂️🙇‍♂️🙇‍♂️
execute 시 마다 별개의 TxManager를 생성하고 동작하도록 변경했습니다.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 TxUserService로 AppUserService를 감싸서 사용하는게 엄청 부자연스럽게 느껴졌어요.
건드려면 일이 커질 것 같아 우선 이렇게 구현하긴 했는데, 주노는 어떠셨나요?

Copy link
Member Author

@Choi-JJunho Choi-JJunho Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Transactional을 코드로 구현한다면 이런 느낌이지않을까? 라는 생각에 저는 이질감이 딱히 없었습니다 😅
흑마법(리플랙션)을 사용하지 않는 방법중에서는 최선이라는 생각입니당

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아무래도 그런 것 같죠? ㅎㅎ


final var newPassword = "newPassword";
final var createBy = "gugu";
// 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다.
assertThrows(DataAccessException.class,
() -> userService.changePassword(1L, newPassword, createBy));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.annotation.Nullable;
import javax.sql.DataSource;
Expand Down Expand Up @@ -48,8 +49,8 @@ private <T> T execute(String sql, Connection connection, PrepareStatementExecuto
}

private <T> T execute(String sql, PrepareStatementExecutor<T> executor, Object... args) {
Connection connection = DataSourceUtils.getConnection(dataSource);
try (
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = getPreparedStatement(sql, connection, args)
) {
return executor.execute(preparedStatement);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd
public static void releaseConnection(Connection connection, DataSource dataSource) {
try {
connection.close();
TransactionSynchronizationManager.unbindResource(dataSource);
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,35 @@

import org.springframework.dao.DataAccessException;

import java.sql.SQLException;
import java.util.function.Supplier;

public class TransactionExecutor {

private TransactionExecutor() {
private final TransactionManager transactionManager;

public TransactionExecutor(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}

public static void execute(final TransactionManager transactionManager, final Runnable runnable) {
public void execute(final Runnable runnable) {
try {
transactionManager.begin();
runnable.run();
transactionManager.commit();
} catch (Exception e) {
try {
transactionManager.rollback();
} catch (SQLException ex) {
throw new DataAccessException(ex);
}
transactionManager.rollback();
throw new DataAccessException(e);
}
}

public <R> R executeWithResult(final Supplier<R> supplier) {
try {
transactionManager.begin();
R result = supplier.get();
transactionManager.commit();
return result;
} catch (Exception e) {
transactionManager.rollback();
throw new DataAccessException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,56 @@
package org.springframework.transaction;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {

private final Connection connection;
private final DataSource dataSource;
private Connection connection;

public TransactionManager(DataSource dataSource) {
this.dataSource = dataSource;
this.connection = DataSourceUtils.getConnection(dataSource);
}

public void begin() {
try {
this.connection = dataSource.getConnection();
if (connection.isClosed()) {
connection = DataSourceUtils.getConnection(dataSource);
}
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new DataAccessException(e);
}
}

public TransactionManager(Connection connection) {
this.connection = connection;
}

public void begin() throws SQLException {
connection.setAutoCommit(false);
}

public void commit() throws SQLException {
connection.commit();
connection.close();
public void commit() {
try {
connection.commit();
this.close();
} catch (SQLException e) {
throw new DataAccessException(e);
}
}

public void rollback() throws SQLException {
connection.rollback();
connection.close();
public void rollback() {
try {
connection.rollback();
this.close();
} catch (SQLException e) {
throw new DataAccessException(e);
}
Comment on lines +37 to +43
Copy link

@0chil 0chil Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

커밋할 때, 그리고 예외로 인한 롤백 시에도 트랜잭션 종료 및 커넥션 제거를 잘 해주고 있네요👍

하나의 쓰레드에서 트랜잭션을 여러 번 실행했을 때,
커넥션이 잘 제거되지 않은 경우 재활용되어 기존 트랜잭션에서 미처 롤백되지 않은 사항이 반영되는 불상사가 생길 수 있습니다.

하지만 주노 코드는 커넥션까지 잘 제거해서 이런 사고를 잘 막을 수 있겠네요!
저는 이 부분 빠뜨렸는데, 잘 배워갑니다!

}

public Connection getConnection() {
return connection;
}

public void close() {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,38 @@

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

public abstract class TransactionSynchronizationManager {

private static final ThreadLocal<Map<DataSource, Connection>> resources = new ThreadLocal<>();

private TransactionSynchronizationManager() {}
private TransactionSynchronizationManager() {
}

public static Connection getResource(DataSource key) {
return null;
Map<DataSource, Connection> connectionWithDataSource = resources.get();
if (connectionWithDataSource == null) {
return null;
}
return connectionWithDataSource.getOrDefault(key, null);
}

public static void bindResource(DataSource key, Connection value) {
Map<DataSource, Connection> connectionWithDataSource = resources.get();
if (connectionWithDataSource == null) {
connectionWithDataSource = new HashMap<>();
resources.set(connectionWithDataSource);
}
Comment on lines +24 to +28
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 해주셨습니다! 👍👍👍💯💯💯

connectionWithDataSource.put(key, value);
}

public static Connection unbindResource(DataSource key) {
return null;
Map<DataSource, Connection> connectionWithDataSource = resources.get();
if (connectionWithDataSource == null) {
return null;
}
return connectionWithDataSource.remove(key);
}
}
Loading