Spring Boot集成Druid数据库连接池

2025-05-29 0 39

1. 前言

Druid数据库连接池由阿里巴巴开源,号称是java语言中最好的数据库连接池,是为监控而生的。Druid的官方地址是:https://github.com/alibaba/druid

通过本文,我们可以看到

  1. Spring Boot 如何配置数据源
  2. Spring Boot 如何集成Druid数据库连接池
  3. 如何打开并访问Druid数据库连接池的监控功能
  4. Spring Boot 使用JdbcTemplate操作数据库

2. 配置pom.xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
<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中配置数据源

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33
# 数据库访问配置,此处使用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,相关代码如下。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31
@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的情况。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
@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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.jianshu.com/p/c8a01ae9f779

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Boot集成Druid数据库连接池 https://www.kuaiidc.com/117141.html

相关文章

发表评论
暂无评论