본문 바로가기
spring

[SpringBoot2] java config로 hikari datasource, transaction aop 설정

by moonsiri 2020. 11. 1.
728x90
반응형

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

 

application.yml

spring:
  datasource:
    hikari:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: "jdbc:mysql://localhost/moonsiri_db?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC&tinyInt1isBit=false"
      username: moonsiri_user
      password: anstlfl_pw
      auto-commit: false     # AOP로 트랜잭션을 제어하기 때문에 false로 사용 (default: true)
      connection-timeout: 30000   # 커넥션 타임 아웃 (30s)
      idle-timeout: 600000   # pool 미사용 커넥션 유지 시간 (10m)
      max-lifetime: 1800000  # pool 에서 미사용 커넥션 최대 수명 시간 (30m)
      minimum-idle: 1        # 최소 커넥션 유지 개수 (default: same as maximumPoolSize)
      maximum-pool-size: 10  # pool에 유지시킬 수 있는 최대 커넥션 수
      pool-name: moonsiri-hikari-pool

 

DatabaseConfig.java

@Configuration
public class DatabaseConfig {

    /**
     * hikari config
     */
    @Bean(name= "hikariConfig")
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public HikariConfig hikariConfig() {
        return new HikariConfig();
    }

    /**
     * datasource
     */
    @Bean(name= "dataSource")
    public HikariDataSource dataSource(@Qualifier("hikariConfig") HikariConfig hikariConfig) {
        return new HikariDataSource(hikariConfig);
    }

    /**
     * sessionfactory
     */
    @Bean(name= "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:sqlmapper/*.xml")); //mapper path
        Objects.requireNonNull(sessionFactoryBean.getObject()).getConfiguration().setMapUnderscoreToCamelCase(true); //camelCase
        return sessionFactoryBean.getObject();
    }

    /**
     * sqlsession
     */
    @Bean(name= "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * transaction manager
     */
    @Bean(name= "txManager")
    public PlatformTransactionManager txManager(@Qualifier("dataSource") DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        dataSourceTransactionManager.setNestedTransactionAllowed(true); // nested
        return dataSourceTransactionManager;
    }
}

 

TransactionConfig.java

@Slf4j
@Aspect
@Configuration
@RequiredArgsConstructor
public class TransactionConfig {

    private final PlatformTransactionManager txManager;

    @Bean
    public TransactionInterceptor txAdvice() {

        TransactionInterceptor txAdvice = new TransactionInterceptor();

        List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
        rollbackRules.add(new RollbackRuleAttribute(Exception.class));

        DefaultTransactionAttribute attribute = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, rollbackRules);
        String transactionAttributesDefinition = attribute.toString();

        Properties txAttributes = new Properties();
        txAttributes.setProperty("insert*", transactionAttributesDefinition);
        txAttributes.setProperty("add*", transactionAttributesDefinition);
        txAttributes.setProperty("create*", transactionAttributesDefinition);
        txAttributes.setProperty("modify*", transactionAttributesDefinition);
        txAttributes.setProperty("update*", transactionAttributesDefinition);
        txAttributes.setProperty("delete*", transactionAttributesDefinition);
        txAttributes.setProperty("remove*", transactionAttributesDefinition);
        txAttributes.setProperty("useTransaction*", transactionAttributesDefinition);

        txAdvice.setTransactionAttributes(txAttributes);
        txAdvice.setTransactionManager(txManager);

        return txAdvice;
    }

    @Bean
    public DefaultPointcutAdvisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com.siri.*Impl.*(..))");

        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }

}

 

 

github.com/brettwooldridge/HikariCP#configuration-knobs-baby

jojoldu.tistory.com/296

blog.jiniworld.me/69

blog.naver.com/zzxx4949/221697782544

728x90
반응형

댓글