spring boot+mybatis+通用mapper+pageHelper+druid的多数据源(非读写分离)

来源:互联网 发布:光猫 lan端口绑定 编辑:程序博客网 时间:2024/06/11 23:36

1、引入依赖(pom.xml)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.jrjzx.regulators.receive</groupId><artifactId>xian-supervision-api-receive</artifactId><packaging>jar</packaging><version>1.0</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.3.RELEASE</version></parent><properties><java.version>1.8</java.version><commons-lang3.version>3.5</commons-lang3.version><weixin4j-base.version>1.7.5</weixin4j-base.version></properties><dependencies> <!-- hot swapping, disable cache for template, enable live reload --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><!-- druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.29</version></dependency><!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>  <!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version></dependency><!--mapper--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!--pagehelper--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- use tomcat7 needed dependency --><dependency><groupId>org.apache.tomcat</groupId><artifactId>tomcat-juli</artifactId><version>${tomcat.version}</version></dependency><!-- https://mvnrepository.com/artifact/com.foxinmy/weixin4j-base --><dependency><groupId>com.foxinmy</groupId><artifactId>weixin4j-base</artifactId><version>${weixin4j-base.version}</version></dependency><!-- apache --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons-lang3.version}</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId></dependency><!-- activemq --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-activemq</artifactId></dependency><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-pool</artifactId></dependency><!-- 监控 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- spring boot starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><!-- log4j2 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency><!-- test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 配置提示 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><!-- <resources><resource><directory>src/main/resources</directory><excludes><exclude>*.properties</exclude></excludes></resource></resources> --></build></project>
2、配置文件(application.properties)

server.port=8180spring.application.name=jrjzx-regulators-receive#profile activespring.profiles.active=prod#log4j2logging.config=classpath:log4j2-${spring.profiles.active}.xml#-----------------------------mybatis pageHelper Mapper-----------------------------#mybatismybatis.configuration.mapUnderscoreToCamelCase=true#print sqlmybatis.configuration.logPrefix=mapper.#mapper#mappers 通用mapper€mapper.not-empty=falsemapper.identity=MYSQL#pagehelperpagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql#----------------------------business dataSource druid-----------------------------spring.datasource.url=jdbc:mysql://10.10.8.226:3306/xian_supervision?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=falsespring.datasource.username=rootspring.datasource.password=xiantest#数据库配置spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driver# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=200# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据spring.datasource.useGlobalDataSourceStat=true#-----------------------------log dataSource druid-----------------------------log.datasource.url=jdbc:mysql://localhost:3306/jrjnew?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=falselog.datasource.username=rejoicelog.datasource.password=rejoice#数据库配置log.datasource.type=com.alibaba.druid.pool.DruidDataSourcelog.datasource.driver-class-name=com.mysql.jdbc.Driver# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大log.datasource.initialSize=5log.datasource.minIdle=5log.datasource.maxActive=200# 配置获取连接等待超时的时间log.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒log.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒log.datasource.minEvictableIdleTimeMillis=300000log.datasource.validationQuery=SELECT 1 FROM DUALlog.datasource.testWhileIdle=truelog.datasource.testOnBorrow=falselog.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小log.datasource.poolPreparedStatements=truelog.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙log.datasource.filters=stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录log.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据log.datasource.useGlobalDataSourceStat=true
3、java配置(多数据源和druid监控)


  默认数据源business(BusinessDatasourceConfig.java)

  

package cn.jrjzx.regulators.receive.config;import java.sql.SQLException;import java.util.Arrays;import org.apache.commons.lang3.StringUtils;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.mybatis.spring.boot.autoconfigure.MybatisProperties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.bind.RelaxedPropertyResolver;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.ApplicationContextException;import org.springframework.context.EnvironmentAware;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.core.env.Environment;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import com.alibaba.druid.pool.DruidDataSource;@Configuration@MapperScan(basePackages = BusinessDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "busSqlSessionFactory")@EnableConfigurationProperties(MybatisProperties.class)public class BusinessDataSourceConfig implements EnvironmentAware { @Autowiredprivate MybatisProperties properties;private static final Logger LOGGER = LoggerFactory.getLogger(BusinessDataSourceConfig.class);    public static final String PACKAGE = "cn.jrjzx.regulators.receive.mapper.business";    public static final String MAPPER_LOCAL = "classpath:mapper/business/*.xml";    private Environment environment;     private RelaxedPropertyResolver propertyResolver;     @Override     public void setEnvironment(Environment environment) {       this.environment = environment;       this.propertyResolver = new RelaxedPropertyResolver(environment,"spring.datasource.");     }     //注册dataSource     @Primary    @Bean(initMethod = "init", destroyMethod = "close")    public DruidDataSource busDataSource(){       if (StringUtils.isBlank(propertyResolver.getProperty("url"))) {         System.out.println("Your database connection pool configuration is incorrect!"             + " Please check your Spring profile, current profiles are:"            + Arrays.toString(environment.getActiveProfiles()));          throw new ApplicationContextException(             "Database connection pool is not configured correctly");       }       DruidDataSource druidDataSource = new DruidDataSource();       druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));       druidDataSource.setUrl(propertyResolver.getProperty("url"));       druidDataSource.setUsername(propertyResolver.getProperty("username"));       druidDataSource.setPassword(propertyResolver.getProperty("password"));       druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));       druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));       druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));       druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));       druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));       druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));       druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));       druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));       druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));       druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));       druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));       druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));       try {druidDataSource.setFilters(propertyResolver.getProperty("filters"));} catch (SQLException e) {LOGGER.error("create business datasource failed, error : {}",e.getMessage());throw new RuntimeException(e);}       return druidDataSource;     }             @Bean(name = "busSqlSessionFactory")    @Primary    public SqlSessionFactory sqlSessionFactory(){        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();        sessionFactoryBean.setDataSource(busDataSource());        //set configuration by hand,it will config before 通用mapper's autoconfiguration        sessionFactoryBean.setConfiguration(properties.getConfiguration());        try {            sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));            return sessionFactoryBean.getObject();        } catch (Exception e) {            LOGGER.error("config business SqlSessionFactory failed,error:{}",e.getMessage());            throw new RuntimeException(e);        }    }    @Primary    @Bean(name = "busTransactionManager")    public DataSourceTransactionManager transactionManager(){return new DataSourceTransactionManager(busDataSource());    }}

其它数据源(LogDataSourceConfig.java)

package cn.jrjzx.regulators.receive.config;import java.sql.SQLException;import java.util.Arrays;import org.apache.commons.lang3.StringUtils;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.mybatis.spring.boot.autoconfigure.MybatisProperties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.bind.RelaxedPropertyResolver;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.ApplicationContextException;import org.springframework.context.EnvironmentAware;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.core.env.Environment;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.annotation.EnableTransactionManagement;import com.alibaba.druid.pool.DruidDataSource;@Configuration@MapperScan(basePackages = LogDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "logSqlSessionFactory")@EnableConfigurationProperties(MybatisProperties.class)public class LogDataSourceConfig implements EnvironmentAware { @Autowiredprivate MybatisProperties properties;private static final Logger LOGGER = LoggerFactory.getLogger(LogDataSourceConfig.class);    public static final String PACKAGE = "cn.jrjzx.regulators.receive.mapper.log";    public static final String MAPPER_LOCAL = "classpath:mapper/log/*.xml";    private Environment environment;     private RelaxedPropertyResolver propertyResolver;     @Override     public void setEnvironment(Environment environment) {       this.environment = environment;       this.propertyResolver = new RelaxedPropertyResolver(environment,"log.datasource.");     }     //注册dataSource     @Bean(initMethod = "init", destroyMethod = "close")    public DruidDataSource logDataSource(){       if (StringUtils.isBlank(propertyResolver.getProperty("url"))) {         System.out.println("Your log database connection pool configuration is incorrect!"             + " Please check your Spring profile, current profiles are:"            + Arrays.toString(environment.getActiveProfiles()));          throw new ApplicationContextException(             "Log Database connection pool is not configured correctly");       }       DruidDataSource druidDataSource = new DruidDataSource();       druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));       druidDataSource.setUrl(propertyResolver.getProperty("url"));       druidDataSource.setUsername(propertyResolver.getProperty("username"));       druidDataSource.setPassword(propertyResolver.getProperty("password"));       druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));       druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));       druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));       druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));       druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));       druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));       druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));       druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));       druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));       druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));       druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));       druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));       try {  druidDataSource.setFilters(propertyResolver.getProperty("filters"));  } catch (SQLException e) {  LOGGER.error("create log datasource failed, error : {}",e.getMessage());  throw new RuntimeException(e);  }         return druidDataSource;       }             @Bean(name = "logSqlSessionFactory")      public SqlSessionFactory logSqlSessionFactory(){          final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();          sessionFactoryBean.setDataSource(logDataSource());          try {          //set configuration by hand,it will config before 通用mapper's autoconfiguration              sessionFactoryBean.setConfiguration(properties.getConfiguration());              sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));              return sessionFactoryBean.getObject();          } catch (Exception e) {              LOGGER.error("config log SqlSessionFactory failed,error:{}",e.getMessage());              throw new RuntimeException(e);          }      }      @Bean(name = "logTransactionManager")      public DataSourceTransactionManager transactionManager(){  return new DataSourceTransactionManager(logDataSource());      }}

整合分布式事物(DataSourcesAutoConfiguration.java)

package cn.jrjzx.regulators.receive.config;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;import org.springframework.context.annotation.Configuration;import org.springframework.data.transaction.ChainedTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.transaction.annotation.EnableTransactionManagement;import org.springframework.transaction.annotation.TransactionManagementConfigurer;import javax.annotation.Resource;/** * Created by :  Sorata   2017/6/27 0027 下午 1:38. */@Configuration@EnableTransactionManagement@ConditionalOnBean({BusinessDataSourceConfig.class,LogDataSourceConfig.class})public class DataSourcesAutoConfiguration  implements TransactionManagementConfigurer{    @Resource    private BusinessDataSourceConfig businessDataSourceConfig;    @Resource    private LogDataSourceConfig logDataSourceConfig;//  配置分布式事务管理    @Override    public PlatformTransactionManager annotationDrivenTransactionManager() {        return  new  ChainedTransactionManager(businessDataSourceConfig.transactionManager(),logDataSourceConfig.transactionManager());    }}

druid监控(DruidConfig.java)

package cn.jrjzx.regulators.receive.config;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;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;@Configuration@ConditionalOnProperty(prefix="druid",name="monitor",havingValue="true")public class DruidConfig {   @Bean   public ServletRegistrationBean druidServlet() {     ServletRegistrationBean reg = new ServletRegistrationBean();     reg.setServlet(new StatViewServlet());     reg.addUrlMappings("/druid/*");     //reg.addInitParameter("allow", "127.0.0.1"); //白名单     //reg.addInitParameter("deny",""); //黑名单     reg.addInitParameter("loginUsername", "admin");     reg.addInitParameter("loginPassword", "admin");     return reg;   }   @Bean public FilterRegistrationBean filterRegistrationBean() {     FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();     filterRegistrationBean.setFilter(new WebStatFilter());     filterRegistrationBean.addUrlPatterns("/*");     filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");     return filterRegistrationBean;    }}


*Mapper接口和*Mapper.xml就省略了,根据上面配置的路径/目录来创建就ok了

over

阅读全文
0 0
原创粉丝点击