트랜잭션

이동건 (불꽃냥펀치)·2025년 2월 15일
0

트랜잭션 이해

데이터를 저장할 때 단순히 파일에 저장해도 되는데 데이터베이스에 저장하는 이유는 무엇일까
여러가지 이유가 있지만 가장 대표적인 이유는 바로 데이터베이스는 트랜잭션이라는 개념을 지원하기 때문이다

트랜잭션은 거래라는 뜻으로 , 데이터베이스에서 트랜잭션은 하나의 거래를 안전하게 처리하도록 보장해 주는 것을 뜻한다. 그런데 하나의 거래를 안전하게 처리하려면 생각보다 고려해야할 점이 많다.

5,000원 계좌이체

  • A의 잔고를 5,000원 감소
  • B의 잔고를 5,000원 증가

계좌이체라는 거래는 2개의 작업이 합쳐져서 하나의 작업처럼 동작해야한다. 만약 1번은 성공했는데 2번에서 문제가 발생하면 계좌이체는 실패하고 A의 잔고만 5,000원 감소하는 심각한 문제가 발생한다.

데이터베이스가 제공하는 트랜잭션을 사용하면 1,2 둘다 성공해야지 정상적으로 로직이 실행되고 둘중 하나라도 실패하면 거래 이전의 상태로 되돌아간다.

모든 작업이 성공해서 데이터베이스에 정상 반영하는 것을 커밋(commit)이라 하고 작업 중 하나라도 실패해서 거래 이전으로 되돌리는 것을 롤백(rollback)이라 한다.

트랜잭션 ACID

  • 원자성: 트랜잭션 내에서 실행한 작업들은 마치 하나의 작업처럼 모두 성공하거나 실패해야 한다
  • 일관성: 모든 트랜잭션은 일관성있는 상태를 유지해야한다
  • 격리성: 동시에 실행되는 트랜잭션들이 서로에게 영향을 미치치 않도록 격리한다
  • 지속성: 트랜잭션을 성공적으로 끝내면 그 결과가 항상 기록되어야 한다

트랜잭션은 원자성,일관성, 지속성을 보장한다. 문제는 격리성인데 트랜잭션간에 격리성을 완벽히 보장하려면 트랜잭션을 거의 순서대로 실행해야한다. 이렇게 하면 동시 처리 성능이 매우 나빠진다. 이런 문제로 인해 ANSI 표준은 트랜 잭션의 격리 수준을 4단계로 나누어 정의했다.



데이터베이스 연결 구조 & DB 세션

데이터베이스 연결 구조

  • 사용자는 웹 어플리케이션 서버(Was)나 DB 접근 툴 같은 클라이언트를 사용해서 데이터베이스 서버에 접근할 수 있다. 클라이언트는 데이터베이스 서버에 연결을 요청하고 커넥션을 맺게된다. 이때 데이터베이스 서버는 내부에 세션이라는 것을 만든다. 앞으로 해당 커넥션을 통한 모든 요청은 이 세션을 통해서 실행된다.

  • 개발자가 클라이언트를 통해 SQl을 전달하면 현재 커넥션에 연결된 세션이 SQl을 실행한다

  • 세션은 트랜잭션을 시작하고 commit,rollback을 통해 트랜잭션을 종료한다

  • 사용자가 커넥션을 닫거나 DBA가 세션을 강제로 종료하면 세션은 종료된다

트랜잭션 - DB 예제 - 개념 이해

트랜잭션 사용법

  • 데이터 변경 쿼리를 실행하고 데이터베이스에 그 결과를 반영하려면 커밋 명령어인 commit을 호출하고 결과를 반영하고 싶지 않다면 롤백 명령어인 rollback을 호출하면 된다
  • 커밋을 호출하기 전까지는 임시로 데이터를 저장하는 것이다. 따라서 해당 트랜잭션을 시작한 세션에게만 변경데이터가 보이고 다른 세션 사용자에게는 변경 데이터가 보이지 않는다

커밋하지않은 데이터 조회 가능 시

  • 데이터를 수정하지 않은 사용자가 변경된 데이터로 로직을 수행했다고 가정해보자. 이때 데이터를 수정한 사용자가 롤백을 수행하면 데이터가 사라져 정합성에 큰 문제가 발생한다

자동 & 수동 커밋

자동 커밋으로 설정하면 각각의 쿼리 실행 직후에 자동으로 커밋을 호출한다. 따라서 커밋이나 롤백을 직접 호출하지 않아도 되는 편리함이 있다. 하지만 쿼리를 하나하나 실행할 때마다 자동으로 커밋이 되어버리기 때문에 트랜잭션 기능을 제대로 수행할 수 없다.

set autocommit true; //자동 커밋 모드 설정
insert into member(member_id, money) values ('data1',10000); //자동 커밋
insert into member(member_id, money) values ('data2',10000); //자동 커밋
  • commit,rollback을 직접 호출하면서 트랜잭션 기능을 제대로 수행하려면 자동 커밋을 끄고 수동 커밋을 사용해야한다
set autocommit false; //수동 커밋 모드 설정
insert into member(member_id, money) values ('data3',10000); 
insert into member(member_id, money) values ('data4',10000); 
commit; //수동 커밋
  • 수동 커밋 모드로 설정하는 것을 트랜잭션을 시작한다고 볼 수 있다
  • 수동 설정을 하면 commit,rollback을 호출해야 함



DB 락

서로 다른 세션에서 데이터를 수정하려고 하면 데이터가 엉킬 가능성이 있다. 이런 문제를 방지하기 위해
세션이 트랜잭션을 시작하고 데이터를 수정하는 동안에는 커밋이나 롤백 전까지 다른 세션에서 해당 데이터를 수정할 수 없게 막아야한다.

락 예제

  • 세션 1은 memberA의 금액을 500원으로 변경하고 싶지만 세션2는 memberA의 금액을 1000원으로 변경하고자 한다
  • 세션1이 트랜잭션을 시작하고 500원으로 변경을 시도할때 세션1은 락을 획득한다.
  • 세션2도 트랜잭션을 시작해 memberA의 데이터를 변경을 시도했지만 락이 없으므로 락이 돌아올 때까지 기다린다
  • 이때 세션2는 락을 무한정 대가허는 것이 아닌라, 락 대기시간을 넘어가면 락 타임아웃 오류가 발생한다
    락 대기시간은 설정 할 수있다.
  • 세션1이 커밋을 실행하고 락을 반납하면 세션2도 락을 획득하고 데이터를 변경 후 커밋한다. 이후 락은 반납한다.
  SET LOCK_TIMEOUT 60000;
  set autocommit false;
  update member set money=1000 where member_id = 'memberA';
  • 락 대기시간 설정 예제 코드



DB 락 - 조회

일반적인 조회는 락을 사용하지 않는다

  • 데이터 변경이 아닌 일반적인 조회는 락이 필요하지 않아 다른 세션이 락을 가지고 있는 상태라도 상관이 없다

  • 데이터를 조회할 때도 락을 획득하고 싶을 때는 select for update구문을 사용하면 된다.

  • 이 경우 세션1이 조회 시점에 락을 가져가버리기 때문에 다른 세션에서 해당 데이터를 변경 할 수 없다.

조회 시점에 락이 필요한 경우

  • 트랜잭션 종료 시점까지 해당 데이터를 다른 곳에서 변경하지 못하도록 강제로 막아야할 때 사용한다
  • 예를 들어서 애플리케이션 로직에서 memberA 의 금액을 조회한 다음에 이 금액 정보로 애플리케이션에서 어떤 계산을 수행한다. 그런데 이 계산이 돈과 관련된 매우 중요한 계산이어서 계산을 완료할 때 까지 memberA 의 금 액을 다른곳에서 변경하면 안된다. 이럴 때 조회 시점에 락을 획득하면 된다



트랜잭션의 적용

비즈니스 로직과 트랜잭션

  • 트랜잭션은 비즈니스 로직이 있는 서비스 계층에서 시작해야 한다. 비즈니스 로직이 잘못되면 해당 비즈니스 로직으로 인해 문제가 되는 부분을 함께 롤백해야하기 때문이다.
  • 트랜잭션을 시작하려면 커넥션이 필요하다. 결국 서비스 계층에서 커넥션을 만들고 트랜잭션 커밋 이후에 커넥션을 종료해야한다.
  • 에플리케이션 DB 트랜잭션을 사용하려면 트랜잭션을 사용하는 동안 같은 커넥션을 유지해야 한다. 그래야 같은 세션을 사용할 수 있다.

MemberRepositoryV2

 @Slf4j
  public class MemberRepositoryV2 {
      private final DataSource dataSource;
      public MemberRepositoryV2(DataSource dataSource) {
          this.dataSource = dataSource;
	}
    public Member save(Member member) throws SQLException {
   		 String sql = "insert into member(member_id, money) values(?, ?)";
  		  Connection con = null;
 	    PreparedStatement pstmt = null;
    	try {
        	con = getConnection();
       	 	pstmt = con.prepareStatement(sql);
        	pstmt.setString(1, member.getMemberId());
        	pstmt.setInt(2, member.getMoney());
        	pstmt.executeUpdate();
        	return member;
    	} catch (SQLException e) {
        	log.error("db error", e);
        	throw e;
    	} finally {
        	close(con, pstmt, null);
		}
	}

public Member findById(String memberId) throws SQLException {
    String sql = "select * from member where member_id = ?";
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = getConnection();
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, memberId);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            Member member = new Member();
            member.setMemberId(rs.getString("member_id"));
            member.setMoney(rs.getInt("money"));
            return member;
        } else {
            throw new NoSuchElementException("member not found memberId="
            + memberId);
            }
        } catch (SQLException e) {
            log.error("db error", e);
            throw e;
        } finally {
            close(con, pstmt, rs);
		}
	}
    public Member findById(Connection con, String memberId) throws
SQLException {
        String sql = "select * from member where member_id = ?";
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, memberId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                Member member = new Member();
                member.setMemberId(rs.getString("member_id"));
                member.setMoney(rs.getInt("money"));
                return member;
            } else {
                throw new NoSuchElementException("member not found memberId="+ memberId);
            }
        } catch (SQLException e) {
            log.error("db error", e);
            throw e;
		} finally {
			//connection은 여기서 닫지 않는다. 
       	 	JdbcUtils.closeResultSet(rs); 
        	JdbcUtils.closeStatement(pstmt);
		}
     }
    public void update(String memberId, int money) throws SQLException {
        String sql = "update member set money=? where member_id=?";
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getConnection();
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, money);
            pstmt.setString(2, memberId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            log.error("db error", e);
            throw e;
        } finally {
            close(con, pstmt, null);
		} 
	}
    public void update(Connection con, String memberId, int money) throws
SQLException {
        String sql = "update member set money=? where member_id=?";
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, money);
            pstmt.setString(2, memberId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            log.error("db error", e);
            throw e;
		} finally {
		//connection은 여기서 닫지 않는다.
          JdbcUtils.closeStatement(pstmt);
        }
    }
    
    public void delete(String memberId) throws SQLException {
        String sql = "delete from member where member_id=?";
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getConnection();
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, memberId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            log.error("db error", e);
            throw e;
        } finally {
            close(con, pstmt, null);
		} 
	}
    private void close(Connection con, Statement stmt, ResultSet rs) {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        JdbcUtils.closeConnection(con);
	}
    private Connection getConnection() throws SQLException {
        Connection con = dataSource.getConnection();
        log.info("get connection={} class={}", con, con.getClass());
        return con;
	} 
}
  • findById(Connection con, String memberId)

  • update(Connection con, String memberId, int money)

    • 커넥션 유지가 필요한 두 메서드는 파라미터로 넘어온 커넥션을 사용해야 한다. 따라서 con = getConnection() 코드가 있으면 안된다.
    • 커넥션 유지가 필요한 두 메서드는 리포지토리에서 커넥션을 닫으면 안된다. 커넥션을 전달 받은 리포지토
      리 뿐만 아니라 이후에도 커넥션을 계속 이어서 사용하기 때문이다. 이후 서비스 로직이 끝날 때 트랜잭션을 종료하고 닫아야 한다.

MemberService2

@Slf4j
  @RequiredArgsConstructor
  public class MemberServiceV2 {
      private final DataSource dataSource;
      private final MemberRepositoryV2 memberRepository;
      public void accountTransfer(String fromId, String toId, int money) throws
  SQLException {
   		Connection con = dataSource.getConnection();
        try {
			con.setAutoCommit(false); //트랜잭션 시작 //비즈니스 로직
			bizLogic(con, fromId, toId, money); 
            con.commit(); //성공시 커밋
		} catch (Exception e) {
			con.rollback(); //실패시 롤백
			throw new IllegalStateException(e);
        } finally {
            release(con);
		}
	}
    
    
    private void bizLogic(Connection con, String fromId, String toId, int
money) throws SQLException {
        Member fromMember = memberRepository.findById(con, fromId);
        Member toMember = memberRepository.findById(con, toId);
        memberRepository.update(con, fromId, fromMember.getMoney() - money);
        validation(toMember);
        memberRepository.update(con, toId, toMember.getMoney() + money);
	}
   
   private void validation(Member toMember) {
        if (toMember.getMemberId().equals("ex")) {
			throw new IllegalStateException("이체중 예외 발생"); }
		}
        
    private void release(Connection con) {
        	if (con != null) {
			try {
			con.setAutoCommit(true); //커넥션 풀 고려
            con.close();
        	} catch (Exception e) {
                log.info("error", e);
			} 
		}
	}
}

출처: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-1

profile
자바를 사랑합니다

0개의 댓글

관련 채용 정보