搭建大型分布式服务(六)SpringBoot整合数据库连接池hikari

·  阅读 797

一、本文要点

接上文,我们已经把SpringBoot整合mybatis了,本文将介绍SpringBoot如何整合数据库连接池HikariCP,管理我们的数据库连接池。什么是HikariCP?可以看下官网介绍。实际上高版本的Springboot默认使用的连接池就是它,这里着重介绍一下如何配置整合。系列文章完整目录

Fast, simple, reliable. HikariCP is a "zero-overhead" production ready JDBC connection pool. At roughly 130Kb, the library is very light. Read about how we do it here.

  • springboot整合HikariCP

  • junit 5 单元测试

  • 自动回滚单元测试操作DB数据

  • springboot + mybatis + Hikari

二、开发环境

  • jdk 1.8
  • maven 3.6.2
  • mybatis 1.3.0
  • springboot 2.4.3
  • mysql 5.6.46
  • junit 5
  • HikariCP
  • idea 2020

三、修改配置文件

修改application-dev.properties文件。

logging.file.path=./logs

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.jdbc-url=jdbc:mysql://9.135.xxx.xxx:3306/mmc?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8
spring.datasource.hikari.username=root
spring.datasource.hikari.password=123456
spring.datasource.hikari.minimum-idle=1
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=primary_pool
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30001
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
spring.datasource.hikari.connection-init-sql=set names utf8mb4

复制代码

五、增加配置类

1、注释掉启动类MemberApplication.java增加@MapperScan。

// @MapperScan(basePackages = "com.mmc.lesson.member.mapper")
@SpringBootApplication
public class MemberApplication {

    public static void main(String[] args) {
        SpringApplication.run(MemberApplication.class, args);
    }

}
复制代码

2、编写MemberService.java,这样写的后续增加多数据源的时候会有好处。

@Configuration
@MapperScan(basePackages = {
        "com.mmc.lesson.member.mapper"}, sqlSessionTemplateRef = "hikariSqlSessionTemplate")
public class MemberDataSourceConfiguration {

    @Bean(name = "hikariDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    /**
     * 会话工厂.
     */
    @Bean(name = "hikariSqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("hikariDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mysqlMappers/*.xml"));
        bean.setVfs(SpringBootVFS.class);
        return bean.getObject();
    }

    /**
     * 目前只有单元测试用到事务.
     */
    @Bean(name = "hikariTransactionManager")
    public PlatformTransactionManager platformTransactionManager(@Qualifier("hikariDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * mybatis用到会话.
     */
    @Bean(name = "hikariSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("hikariSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

复制代码

六、运行一下

1、编写单元测试。

@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional // 自动回滚单元测试插入DB的数据
public class MemberServiceTest {

    @Resource
    private MemberService memberService;

    /**
     * add.
     */
    @Test
    public void testAdd() {

        TblMemberInfo member = new TblMemberInfo();
        member.setUname("zhangsan");
        member.setUsex(1);
        member.setUbirth(new Date());
        member.setUtel("888");
        member.setUaddr("凌霄殿");
        member.setState(0);
        member.setDelFlag(0);
        member.setUphoto(null);

        TblMemberInfo ret = memberService.save(member);

        Assertions.assertThat(ret).isNotNull();
        log.info("--------------------------------------------------");
        log.info(ret.getUname());


    }

}
复制代码

2、效果。

[2021-02-25 12:03:41.974] [main] [DEBUG] [c.m.l.member.mapper.TblMemberInfoMapper.insert:?] - ==> Parameters: null, zhangsan(String), 1(Integer), 2021-02-25 12:03:41.729(Timestamp), 888(String), 凌霄殿(String), null, null, 0(Integer), 0(Integer), null
[2021-02-25 12:03:41.990] [main] [DEBUG] [c.m.l.member.mapper.TblMemberInfoMapper.insert:?] - <==    Updates: 1
[2021-02-25 12:03:41.991] [main] [DEBUG] [org.mybatis.spring.SqlSessionUtils:?] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2d64c100]
[2021-02-25 12:03:42.032] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:?] - --------------------------------------------------
[2021-02-25 12:03:42.032] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:?] - zhangsan
复制代码

七、小结

有同学留言说怎样使用阿里的druid作为数据库连接池,不急后面会介绍,完整代码地址:戳这里。下一篇《搭建大型分布式服务(七)SpringBoot整合数据库连接池druid》

加我一起交流学习!

分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改