上一篇SpringBoot基础已经配置SpringMVC,在简化配置之后,只要了解基本的注解就可以配置一个SSM框架。出来后一直没怎么用Hibernate,觉得太重不太灵活,自从用了MyBatis就放不下,SQL灵活可以运用。
现在的数据库连接池也比较多了,常见的c3p0,dbcp等等优缺点各有,公司一直用的Druid阿里巴巴出品,区别在与可以查看sql运行状况监控你应用的数据库访问情况。
1.首先在pom.xml增加相关的依赖
<!--支持使用 JDBC 访问数据库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- druid阿里巴巴数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
<!-- MySql数据库驱动 -->
<dependency>
<groupId> mysql</groupId>
<artifactId> mysql-connector-java</artifactId>
<version> 5.0.5</version>
</dependency>
2.配置数据库连接池DruidConfiguration以及监控界面
1.首先在resources路径下创建application.properties
SpringBoot会自动读取该配置,在使用SpringBoot的过程中,会经常使用到该配置文件,主要配置数据库的相关信息
# 数据库访问配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
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,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true
2.通过继承EnvironmentAware接口读取配置文件创建DateSource
@Configuration
public class DruidConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment env) {
// TODO Auto-generated method stub
this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
}
/**
* 注册dataSouce,这里作为一个例子,只注入了部分参数信息,其它的参数自行扩散思维。
* @param driver
* @param url
* @param username
* @param password
* @param maxActive
* @return
*/
@Bean
public DataSource druidDataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
System.out.println("DruidConfiguration.druidDataSource(),url="+propertyResolver.getProperty("url")+",username="+propertyResolver.getProperty("username")+",password="+propertyResolver.getProperty("password"));
try {
datasource.setFilters("stat, wall");
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
}
这样一个DataSources就创建完毕
3.配置Druid监控界面
只需要在配置DateSources的类注册Servler,Filter就可以
/**
* 注册一个StatViewServlet
* @return
*/
@Bean
public ServletRegistrationBean DruidStatViewServle(){
//org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//添加初始化参数:initParams
//白名单:
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
//servletRegistrationBean.addInitParameter("deny","192.168.1.73");
//登录查看信息的账号密码.
servletRegistrationBean.addInitParameter("loginUsername","admin2");
servletRegistrationBean.addInitParameter("loginPassword","123456");
//是否能够重置数据. 禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
/**
* 注册一个:filterRegistrationBean
* @return
*/
@Bean
public FilterRegistrationBean druidStatFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则.
filterRegistrationBean.addServletNames("druidWebStatFilter");
filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
return filterRegistrationBean;
}
4.最后配置MyBatis
1.在Application中增加扫描mapper的注解
@SpringBootApplication
@MapperScan("com.fivefu.springboot.mapper")
public class Application {
private static Logger logger = Logger.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
logger.info("============= SpringBoot Start Success =============");
}
}
2.配置扫描mapper.xml的bean以及事务管理
//设置mybatis路径
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(druidDataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(druidDataSource());
}
至此一个Spring+Mybatis+SpringMVC的配置就完毕了启动后访问http://localhost:8099/druid/login.html即可访问数据监控界面