1. 程式人生 > >Spring boot+Mybatis+druid連線池及監控資訊配置

Spring boot+Mybatis+druid連線池及監控資訊配置

新建專案

我是用的是IDEA,專案選擇如下所示:

為專案取一個名字,如下圖所示,然後點選next

選擇需要新增的模組,選擇完畢後,會自動將所需的依賴,新增到pom檔案中

確認路徑無誤,點選finish即可

專案基本結構,IDEA會自動生成,為了測試環境是否可以成功執行,建議建包結構如下:

專案生成後的pom檔案內容如下:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

我們需要自己新增druid的依賴資訊,如下:

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.10</version>
</dependency>

下邊,開始對配置檔案進行配置,在springboot中,所有的配置資訊都可以在application.properties中進行,下邊是基本的配置資訊:包括druid連線池的一些配置,我使用的是8.x版本的mysql,與之前版本的會有稍微的不同,可去官網查閱。

# 使用druid連線池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 資料庫的URL、帳號、密碼、驅動,dbname是自己資料庫中表空間的對應的名字,請修改為自己本地一致的
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/dbname?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name=com.mysql.cj.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
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# MyBatis 配置
# mybatis的mapper.xml檔案的路徑
mybatis.mapper-locations=classpath:mapper/*.xml
# mybatis的model所在的包
mybatis.type-aliases-package=com.littlebird.storm.system.model

資訊配置完畢後,我們就可以進行mybatis是否可行的測試。

分別建立service,controller,dao,model和mapper.xml等檔案,如下所示:

controller

package com.littlebird.storm.system.controller;

import com.littlebird.storm.system.model.User;
import com.littlebird.storm.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/find")
    public User findByName(){
        /*因為沒寫前端頁面,這裡寫了些偽業務程式碼*/
        User user =userService.findByName("李四");
        return user;
    }

    @RequestMapping("/findall")
    public List<User> findAll(){
        List<User> users =userService.findAll();
        return users;
    }
}

service

package com.littlebird.storm.system.service;

import com.littlebird.storm.system.dao.UserDao;
import com.littlebird.storm.system.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public User findByName(String name){
        User user =userDao.findByName(name);
        return user;
    }

    public List<User> findAll(){
        List<User> users =userDao.findAll();
        return users;
    }
}

model

package com.littlebird.storm.system.model;

public class User {
    private long userId;
    private String userName;
    private String password;
    private String phone;

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

dao

package com.littlebird.storm.system.dao;

/*@Mapper*/
/*@Repository也可以不用新增,但是不新增之後使用@Autowired注入介面是IDEA會提示紅線,但是不影響編譯執行*/
/*@Mapper如果配置了自動掃描,這個註解可以不新增,也推薦使用自動掃描*/

import com.littlebird.storm.system.model.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {

    /*xml方式*/
    User findByName(String userName);
    /*註解方式*/
    @Select("select * from t_user")
    List<User> findAll();
}

mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--名稱空間,指定對應的Dao-->
<mapper namespace="com.littlebird.storm.system.dao.UserDao">

    <!--使用resultType指定輸出型別-->
    <select id="findByName" resultType="User">
        SELECT * FROM t_user WHERE username = #{userName}
    </select>

</mapper>

資料庫表資訊如下,可以自行建立,很簡單的表格:


測試可以使用IDEA自帶的測試工具,很好用,如下圖所示:

由於版本不同,可能所在位置不一樣,但是都在tool下,開啟後是這樣的:

測試完畢後,如果能正確返回結果,則表示專案搭建成功!

下邊開始配置druid監控服務,如圖所示新增DruidConfig.java檔案,

在其中配置druid監控服務的servlet和filter,在spring boot中有專門配置servlet和filter的方法,包括註解方式和Bean方式,我們採用bean方式,程式碼如下:

package com.littlebird.storm.core.database.druid;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        //配置使用者名稱
        reg.addInitParameter("loginUsername", "root");
        //配置密碼
        reg.addInitParameter("loginPassword", "root");
        //在日誌中列印執行慢的sql語句
        reg.addInitParameter("logSlowSql", "true");
        //另外還可配置黑白名單等資訊,可參考druid官網介紹
        return reg;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        //過濾檔案型別
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        //監控單個url呼叫的sql列表
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }

}

配置完畢後,我本地地址是http://localhost:8080/druid,就可以進行登入訪問了,但是此時,點選資料來源一欄,是沒有任何資料來源的,如下圖所示:

下邊,我們來進行資料來源的配置,在上圖中已經給過目錄結構,分別建立DruidBean.java和MyBatisConfig.java,內容分別如下:

DruidBean.java

package com.littlebird.storm.core.database.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

@Component
//可以將application.properties中字首為spring.datasource的配置項,自動注入到當前bean中
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidBean {

    private String url;

    private String username;

    private String password;

    private String driverClassName ;

    private Integer initialSize = 2;

    private Integer minIdle = 1;

    private Integer maxActive = 20;

    private Integer maxWait = 60000;

    private Integer timeBetweenEvictionRunsMillis = 60000;

    private Integer minEvictableIdleTimeMillis = 300000;

    private String validationQuery = "SELECT 'x'";

    private Boolean testWhileIdle = true;

    private Boolean testOnBorrow = false;

    private Boolean testOnReturn = false;

    private Boolean poolPreparedStatements = true;

    private Integer maxPoolPreparedStatementPerConnectionSize = 20;

    private String filters = "stat";

    public void config(DruidDataSource dataSource) {

        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(initialSize);     //定義初始連線數
        dataSource.setMinIdle(minIdle);             //最小空閒
        dataSource.setMaxActive(maxActive);         //定義最大連線數
        dataSource.setMaxWait(maxWait);             //最長等待時間

        // 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

        // 配置一個連線在池中最小生存的時間,單位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);

        // 開啟PSCache,並且指定每個連線上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public Integer getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public Boolean getTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(Boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public Boolean getTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(Boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public Boolean getTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(Boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public Boolean getPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }

    public Integer getMaxPoolPreparedStatementPerConnectionSize() {
        return maxPoolPreparedStatementPerConnectionSize;
    }

    public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
        this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
    }

    public String getFilters() {
        return filters;
    }

    public void setFilters(String filters) {
        this.filters = filters;
    }
}

上述類建立完成後,IDEA會有一個提示,是因為沒有開啟配置檔案屬性值自動注入的功能,新增一個依賴就可以了,如下:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
</dependency>

MybatisConfig.java

package com.littlebird.storm.core.database.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import com.littlebird.storm.core.database.druid.DruidBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MybatisConfig {

    @Autowired
    DruidBean druidProperties;

    /**
     * guns的資料來源
     */
    private DruidDataSource dataSourceStrom() {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }

    /**
     * 單資料來源連線池配置
     */
    @Bean(initMethod = "init",destroyMethod = "close")
    public DruidDataSource dataSource() {
        return dataSourceStrom();
    }


}

重新啟動環境,就可以看見資料來源啦,配置完畢。