SpringBoot整合 Mybatis+druid连接池,监控+多数据源配置+tkmybatis

1.tk.mybatis 通用Mapper 很好用的 mybatis 插件。

2.druid,阿里巴巴出品的sql连接池,监控,很强大的一个应用。

3.项目中有时候不止一个数据源,可能会有多个,那就需要自己配置了

A.SpringBoot 整合 Mybatis

1.配置pom坐标

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
        
            mysql
            mysql-connector-java
        

加入  mybatis-spring-boot-starter 和 mysql-connector-java

2.配置 application.yml 文件:

spring:
  datasource:
    base:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/zhangzq?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
      username: root
      password: root

这样配置是为了更好的配置多数据源。但数据源的时候也可以这样配置,如果想不自己配置 DataSource 则 直接配 spring.datasource.url 这样...

3.配置DataSource

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;
import com.alibaba.druid.pool.DruidDataSource;

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

@Configuration
@MapperScan(
    // 此处的mapper 可以有多个
    basePackages = { BaseDataSourceConfig.MAPPER_PACKAGE },
    sqlSessionFactoryRef = "baseSqlSessionTemplate"
)
public class BaseDataSourceConfig {

    // mapper 的xml存放路径
    protected final static String MAPPER_XML_AREA = "classpath:com/zzq/zhangzq/mapper/*.xml";
    // mapper.java 存放路径,被@MapperScan扫描的,注入 sqlsession的
    protected final static String MAPPER_PACKAGE = "com.zzq.zhangzq.mapper";

    @Value("${spring.datasource.base.url}")
    private String url;

    @Value("${spring.datasource.base.username}")
    private String user;

    @Value("${spring.datasource.base.password}")
    private String password;

    @Value("${spring.datasource.base.driver-class-name}")
    private String driverClass;


    /**
     * 注入 datasource
     * @return
     */
    @Bean(name = "baseDataSource")
    @ConfigurationProperties( prefix = "spring.datasource.base")
    @Primary
    public DataSource setDataSource()  {
        // 使用druid 则这样注入 dataSource,不需要则直接 DataSourceBuilder.create().build()
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        try {
            // 如果想使用 Druid 的sql监控则,此处需要写 stat
            dataSource.setFilters("stat");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 注入 事务,在 serviceImpl 的时候使用
     * @return
     */
    @Bean(name = "baseTransationManager")
    @Primary
    public DataSourceTransactionManager setTransactionManager(){
        // 传入 dataSource
        return new DataSourceTransactionManager( setDataSource() );
    }

    /**
     * 注入 sqlSession
     * @return
     * @throws Exception
     */
    @Bean(name = "baseSqlSessionTemplate")
    @Primary
    public SqlSessionFactory setSqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(setDataSource());
        // 设置mapper.xml 扫描路径
        bean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources(BaseDataSourceConfig.MAPPER_XML_AREA) );
        return bean.getObject();
    }

}

注意:如果使用的是 tkmybatis , 注解中的  MapperScan 是 tk.mybatis.spring.annotation.MapperScan 包下的。如果用成 mybatis包i下的了则会报错。里面的注释可以看看

4.tk.mybatis

        
            tk.mybatis
            mapper-spring-boot-starter
            1.2.4
        

tkmybatis ,基本上不需要怎么配置,很好用,Mapper的继承就ok了,下面我会给出代码的。

B.druid

1.pom.xml

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

2.配置:

import com.alibaba.druid.support.http.StatViewFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

import java.util.HashMap;
import java.util.Map;

/**
 * druid 配置.
*/
@Configuration
public class DruidConfiguration {

    /*
     * 注册过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean setDruidFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setFilter( new WebStatFilter());
        Map initParameters = new HashMap<>();
        initParameters.put("exclusions", "*.js,*.html,*.gif,*.jpg,*.png,*.css,*.ico,*.jsp,/druid/*,/download/*");
        filterRegistrationBean.setInitParameters( initParameters );
        return filterRegistrationBean;
    }

    /**
     * 注册一个StatViewServlet
     * @return
     */
    @Bean
    public ServletRegistrationBean setDruidServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet( new StatViewServlet() );
        servletRegistrationBean.addUrlMappings("/druid/*");

        Map initParameters = new HashMap<>();
        initParameters.put("resetEnable", "false"); //禁用HTML页面上的“Rest All”功能
        initParameters.put("allow", "");  //ip白名单(没有配置或者为空,则允许所有访问)
        initParameters.put("loginUsername", "maxwell");  //++监控页面登录用户名
        initParameters.put("loginPassword", "pkusoft");  //++监控页面登录用户密码
        initParameters.put("deny", ""); //ip黑名单
        //如果某个ip同时存在,deny优先于allow
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }
}

注意此处的类不要写错了。写错了会出问题的。比如说访问 /druid/ 的时候重定向过多,filter 不执行

C.多数据源配置

1.application.yml 配置

刚才配置的时候,就没有按照官方默认的方式写,就是为了好配多数据源,

spring:
  datasource:
    base:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/zhangzq?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
      username: root
      password: root
    licm:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/licm?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
      username: root
      password: root

2.配置从数据源

配置从数据源和配置主数据源差不多,类似,配置主数据源一定要加上 @Primary,从数据源则不需要。


@Configuration
@MapperScan(
        basePackages = {"com.zzq.licm.mapper"},
        sqlSessionFactoryRef = "licmSqlSession"
)
public class LicmDataSourceConfig {

    @Value("${spring.datasource.licm.url}")
    private String url;

    @Value("${spring.datasource.licm.username}")
    private String user;

    @Value("${spring.datasource.licm.password}")
    private String password;

    @Value("${spring.datasource.licm.driver-class-name}")
    private String driverClass;

    @Bean(name = "licmDataSource")
    public DataSource setDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        try {
            dataSource.setFilters("stat");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "licmTransation")
    public DataSourceTransactionManager setTransationManager(){
        return new DataSourceTransactionManager(setDataSource());
    }

    @Bean(name = "licmSqlSession")
    public SqlSessionFactory setSqlSession() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(setDataSource());
        bean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:com/zzq/licm/mapper/*.xml"));
        return bean.getObject();
    }

}

3.配置启动器,mapper 之类的,先不放了,等下直接把源码放出来

@SpringBootApplication
public class Application {

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

}

D.项目结构

SpringBoot整合 Mybatis+druid连接池,监控+多数据源配置+tkmybatis_第1张图片

请大家结合源码看该文章,省略部分为  mapper,service,impl.controller

使用 tk.mybatis 所有的Mapper 都要继承 tkmybatis  的Mapper

源码地址:https://github.com/winterme/pkusoft

 

你可能感兴趣的:(springboot,druid,tkmybatis,SpringBoot菜鸟教程)