사용자 도구

사이트 도구


springframework:transaction

문서의 이전 판입니다!


Spring Transaction

interface or class?

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies ( proxy-target-class=“true”) or the weaving-based aspect ( mode=“aspectj”), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.

Read Only

@Transactional(readOnly=true)는 JDBC의 Connection.setReadOnly(true)를 호출한다. 이는 단지 “힌트”일 뿐이며 실제 데이터베이스 자체를 read-only 트랜잭션으로 생성할지 여부는 JDBC 드라이버에 따라 달라지고 행위도 데이터 계층 프레임워크의 구현여부에 따라 달라질 수 있다.

이 힌트로 정말로 read only 트랜잭션이 생성될 수도 있고, MySQL 리플리케이션 JDBC 드라이버의 경우 Write가 있을 경우에는 Master로 read only일 경우에는 Slave로 커넥션을 맺는 식의 선택을 하는 정도의 역할만 할 수도 있다.

Oracle JDBC 드라이버는 Read-Only 트랜잭션을 지원하며, MySQL의 경우 5.6.5 버전이 되어서야 이를 지원하게 되었다.

Spring-Hibernate 연동시에는 Session의 Flush Mode를 FLUSH_NEVER로 변경한다. 그러나 데이터가 수정되면 수정된 상태로 세션의 1차 캐시에는 수정된 상태로 데이터가 남아있게 되면, 명시적으로 flush()를 호출하면 쓰기 기능이 작동하게 된다.

단, 읽기 작업만 하더라도 트랜잭션을 걸어주는 것이 좋다. 트랜잭션을 걸지 않으면 모든 SELECT 쿼리마다 commit을 하기 때문에 성능이 떨어진다. 명시적으로 트랜잭션을 걸어주면 마지막에 명시적으로 commit을 해주면 되며, commit 횟수가 줄어서 성능이 좋아진다.

Chained Transaction Manager

  • ChainedTransactionManager Spring Data 에 추가된 다중 트랜잭션을 연결해서 관리하는 트랜잭션 매니저.
  • JTA 처럼 트랜잭션이 완전히 동기화 되는 것은 아니고, 여러 트랜잭션을 묶어서 순서대로 커밋/롤백을 진행하는 방식.
  • JTA 수준은 아니더라도 여러 트랜잭션이 생성되는 애플리케이션에서 각자 @Transactional을 지정하지 않고 하나로 통일하고자 하는 경우에 괜찮을 듯.
  • Chained Transaction Manager로 묶이는 각 트랜잭션의 Connection Pool 의 min/max 갯수는 동일하게 가져가야한다.
  • 경험상, 서로 다른 동기화 시점을 가지는 트랜잭션은 묶지 않는 것이 좋다.
    • MQ 사용시, MQ로 받은 데이터를 저장하는데 DB 접속이 끊겼을 경우 retry 를 하고자 한다면 MQ 트랜잭션과 DB 트랜잭션을 함께 묶으면 이 작업이 안된다. DB 트랜잭션이 롤백 될때 MQ 트랜잭션까지 롤백 되어 버려서 재시도할 트랜잭션이 없어지기 때문이다.

Transaction 정보 처리

익명 Anonymous Class에서 현재 서비스의 메소드 호출

  • 트랜잭션이 걸린 서비스메소드에서 익명 클래스를 리턴하여 서비스 클래스의 다른 메소드를 호출하게 하면 트랜잭션이 올바르게 작동하지 않는다.
        @Override
        @Transactional(readOnly = true)
        public Iterable<Book> findAll() {
            // true
            log.info("Outside : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            return new Iterable<Book>() {
                @Override
                public Iterator<Book> iterator() {
                    // false
                    log.info("In iterable : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    return findAllReal().iterator();
                }
            };
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<Book> findAllReal() {
            // false
            log.info("Inside : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            return bookRepository.findAll();
        }
  • 익명 클래스에서 트랜잭션을 올바로 걸고자 한다면 트랜잭션이 없는 외부에서 익명 클래스를 생성하면서 트랜잭션이 있는 서비스 Bean을 그 안으로 넘겨주어야 한다.
    // BookAnotherService
    @Autowired
    private BookService bookService;
     
    @Transactional(readOnly = true)
    public Iterable<Book> findAll() {
        // true
        log.info("Outside : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
        return new Iterable<Book>() {
            @Override
            public Iterator<Book> iterator() {
                // false -> Transaction 영역이 아니므로 false가 맞음.
                log.info("In iterable : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                return bookService.findAllReal().iterator();
            }
        };
    }
     
    // BookService
    @Override
    @Transactional(readOnly = true)
    public List<Book> findAllReal() {
        // true
        log.info("Inside : readOnly {}", TransactionSynchronizationManager.isCurrentTransactionReadOnly());
        return bookRepository.findAll();
    }

Timeout

  • PlatformTransactionManager#setDefaultTimeout 을 통해 기본 timeout 시간을 지정할 수 있다. 기본값은 -1로 JDBC Driver 기본을 따르거나 무제한을 의미한다.
  • @Transactional(timeout=“”)을 통해서 각 단위별로 지정가능하다.
springframework/transaction.1444639308.txt.gz · 마지막으로 수정됨: 2015/10/12 17:11 저자 kwon37xi