整合DRUID数据源
Druid是一个数据库连接池,加入了日志监控
Druid可以很好的监控数据库池链接和sql的执行情况
- 引入数据源
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.6</version> </dependency>
- 在application配置文件中加上type属性,以指定数据源
spring: datasource: username: xxx password: xxx url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimeZone=UTC driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource
- 此时使用测试查看数据源
输出的是:@SpringBootTest class DemoApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { // 查看数据源 System.out.println(dataSource.getClass()); // 获得数据库连接 Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } }
可见数据源已经变成了druid,但底层使用的仍然是jdbc的实现(java数据库的底层永远都是jdbc)class com.alibaba.druid.pool.DruidDataSource com.mysql.cj.jdbc.ConnectionImpl@3dd31157
- 继续配置数据源,注意所有的配置均在spring.datasource下面完成
注意需要导入Log4j依赖<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- Druid 数据源具有监控的功能,并提供了一个 web界面方便用户查看。所以第一步需要设置 Druid 的后台管理页面。
然后访问http://localhost:8080/druid就会自动跳转到http://localhost:8080/druid/login.html登录页面package com.example.demo.config; @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource duridDataSource(){ return new DruidDataSource(); } // 后台监控 @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> statViewServletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); // 后台有人登录,账号密码配置 HashMap<String,String> initParamters=new HashMap<>(); // 增加配置 initParamters.put("loginUsername","admin"); //登录的key是固定的 loginUsername loginPassword initParamters.put("loginPassword","123"); // 允许谁可以访问 initParamters.put("allow",""); // value为空,代表谁都可以访问 statViewServletRegistrationBean.setInitParameters(initParamters); // 设置初始化参数 return statViewServletRegistrationBean; } }
按照配置的账号密码登入后,就会进入 Druid 的后台管理页面:
此时我们访问http://localhost:8080/list(见博文)来执行一条查询sql语句,随后在sql监控页面就会出现一条记录