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=8180
spring.application.name=jrjzx-regulators-receive
#profile active
spring.profiles.active=prod
#log4j2
logging.config=classpath:log4j2-${spring.profiles.active}.xml
#-----------------------------mybatis pageHelper Mapper-----------------------------
#mybatis
mybatis.configuration.mapUnderscoreToCamelCase=true
#print sql
mybatis.configuration.logPrefix=mapper.
#mapper
#mappers 通用mapper
mapper.not-empty=false
mapper.identity=MYSQL
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.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=false
spring.datasource.username=root
spring.datasource.password=xiantest
#数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=200
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.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=false
log.datasource.username=rejoice
log.datasource.password=rejoice
#数据库配置
log.datasource.type=com.alibaba.druid.pool.DruidDataSource
log.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
log.datasource.initialSize=5
log.datasource.minIdle=5
log.datasource.maxActive=200
# 配置获取连接等待超时的时间
log.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
log.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
log.datasource.minEvictableIdleTimeMillis=300000
log.datasource.validationQuery=SELECT 1 FROM DUAL
log.datasource.testWhileIdle=true
log.datasource.testOnBorrow=false
log.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
log.datasource.poolPreparedStatements=true
log.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 {
@Autowired
private 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 {
@Autowired
private 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








网友评论