1. 前言
Druid数据库连接池由阿里巴巴开源,号称是java语言中最好的数据库连接池,是为监控而生的。Druid的官方地址是:https://github.com/alibaba/druid
通过本文,我们可以看到
- Spring Boot 如何配置数据源
- Spring Boot 如何集成Druid数据库连接池
- 如何打开并访问Druid数据库连接池的监控功能
- Spring Boot 使用JdbcTemplate操作数据库
2. 配置pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
3. 在application.properties中配置数据源
# 数据库访问配置,此处使用postgres为例。
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://192.168.1.9/jianshudb
spring.datasource.username=postgres
spring.datasource.password=yourpassword
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# Oracle请使用select 1 from dual
spring.datasource.validationQuery=SELECT 'x'
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
DruidDataSource参考配置:
https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_DruidDataSource%E5%8F%82%E8%80%83%E9%85%8D%E7%BD%AE
4. 打开Druid的监控统计功能
Druid的监控统计功能是通过filter-chain扩展实现,如果你要打开监控统计功能,需要配置StatFilter,相关代码如下。
@Configuration
public class DruidConfiguration {
private static final Logger log = LoggerFactory.getLogger(DruidConfiguration.class);
@Bean
public ServletRegistrationBean druidServlet() {
log.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("loginUsername", "admin");// 用户名
initParameters.put("loginPassword", "admin");// 密码
initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问)
//initParameters.put("deny", "192.168.20.38");// IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
}
@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;
}
}
等应用启动后,可以访问地址:http://localhost:8080/druid/,用户名和密码见上述代码中的设置,即admin/admin。
5. 使用JdbcTemplate操作数据库
假设数据库中有表t_user,其中id=1的user的username为ZhangSan。下面的例子演示了通过id查找username的情况。
@RestController
public class DemoController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping(value = "/hello.do", method = RequestMethod.GET)
public String hello(@RequestParam(value = "id", required = true) Integer id) {
String name = getNameById(id);
return (name == null) ? "Hello World" : ("Hello " + name);
}
public String getNameById(Integer id) {
String sql = "select username from t_user where id = ? ";
List<String> list = jdbcTemplate.queryForList(sql, new Object[] {id}, String.class);
return list.isEmpty() ? null : list.get(0);
}
}
访问地址:http://localhost:8080/hello.do?id=1
结果输出:Hello, ZhangSan