Springboot 系列(九)使用 Spring JDBC 和 Druid 數據源監控


前言

作為一名 Java 開發者,相信對 JDBC(Java Data Base Connectivity)是不會陌生的,JDBC作為 Java 基礎內容,它提供了一種基准,據此可以構建更高級的工具和接口,使數據庫開發人員能夠編寫數據庫應用程序。下面演示下 Springboot 中如何使用 JDBC 操作,並配置使用 Druid 連接池,體驗 Druid 對數據庫操作強大的監控和擴展功能。Alibaba-Durid 官方手冊點這里

1. 數據庫准備

使用mysql數據庫創建數據庫 springboot,並在庫中新建數據表 user 並新增兩條信息。

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `password` varchar(32) NOT NULL,
  `skills` varchar(255) DEFAULT NULL,
  `username` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

# 新增數據
INSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (1, 17, '2019-01-12 21:02:30', '123', 'Go', 'Darcy');
INSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (3, 23, '2019-01-01 00:11:22', '456', 'Java', 'Chris');

2. 添加依賴

新建一個 Springboot項目,這里不說。添加依賴如下。

    <dependencies>
        <!-- spring jdbc 操作模版 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- springboot web開發 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mysql 數據庫連接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 引入druid數據源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

3. 配置數據源信息

常規的 JDBC 配置不需要配置這么多內容,這里因為使用了 Druid 連接池,所以配置了 Druid 部分。對自動配置不理解的可以查看系列文章Springboot 系列(二)Spring Boot 配置文件

spring:
  datasource:
    username: root
    password: 123
    url: jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用於防火牆
    filters: stat
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

配置完畢之后,配置信息還不能綁定到 Druid數據源中,還需要新建一個配置類綁定數據源和配置信息。

/**
 * <p>
 * Druid 數據源配置
 *
 * @Author niujinpeng
 * @Date 2019/1/14 22:20
 */
@Configuration
public class DruidConfig {
    /**
     * 配置綁定
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druid() {
        return new DruidDataSource();
    }
}

到這里,數據源已經配置完畢,編寫測試方法測試 druid 連接池是否生效。


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDataJdbcApplicationTests {
    @Autowired
    DataSource dataSource;
    /**
     * 測試JDBC數據源
     * @throws SQLException
     */
    @Test
    public void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

運行看到 contextLoads 輸出信息。

class com.alibaba.druid.pool.DruidDataSource
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-02-27 14:14:56.144  INFO 12860 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@3e104d4b

輸出日志中的 com.alibaba.druid 說明 Druid 已經生效。

4. 使用 Spring-JDBC

傳統的 JDBC 使用中,需要編寫大量代碼,從構造 PreparedStatement 到查詢不勝其煩。面對這樣的開發痛點,Spring 封裝了 Spring-jdbc. 讓我們使用 JdbcTemplate 即可輕松的操作數據庫。Spring-jdbc 的詳細使用不是這篇文章重點,只簡單演示下是否生效。
編寫控制器,查詢一個 user 信息。

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/query")
    public Map<String, Object> map() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * FROM user");
        return list.get(0);
    }
}

啟動spring 項目,請求 /query 接口得到正常響應。

{
"id": 1,
"age": 17,
"birthday": "2019-01-12T13:02:30.000+0000",
"password": "123",
"skills": "Go",
"username": "Darcy"
}

可見 Spring-JDBC 已經從數據庫中取出了數據信息。

5. 使用 Druid 監控

如果使用 Druid 連接池卻不使用監控功能,那么就有點暴殄天物了。下面開始配置 Druid 的 SQL 監控功能。在上面寫的 DruidConfig 配置類中增加配置 Druid 的 Servlet 和 Filter.

 	/**
     * Druid的servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123");
        initParams.put("allow","127.0.0.1");
        bean.setInitParameters(initParams);
        bean.setUrlMappings(Arrays.asList("/druid/*"));
        return bean;
    }
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        HashMap<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "/css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

上面配置了 Druid 監控訪問路徑為 /druid、登錄用戶是 admin、登錄密碼是123、允許訪問的IP是127.0.0.1 本機、不需要監控的請求是 /css/druid 開頭的請求。

重新啟動項目,訪問測試 /query,然后訪問 /durid 登錄頁。
Druid 登錄頁

登錄后可以看到 SQL 監控信息和 URL 監控等信息。
SQL 監控

URL 監控。
URL 監控

文章代碼已經上傳到 GitHub Spring Boot jdb

本文作者: 雪漫士兵
我的微信:wn8398
原文出處: www.codingme.net
本片文章是博主原創文章,歡迎轉載,轉載時在明顯位置注明原文鏈接即可。
如果覺得這篇內容有趣好玩有幫助,不妨關注公眾號點個好看推薦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM