Spring Boot 整合Druid搭建初始化項目

前言

項目組要搭建一個xxx的後臺管理系統
技術選型:
項目:Spring Boot
數據庫鏈接池:Druid
數據庫:Oracle或者mysql
JS:VueJS
Html和CSS:Boostrapcss

1、搭建Spring Boot框架

step1
https://start.spring.io/ 進入此URL,在左邊兩欄配置本身的GroupID和ArtifactID,在右邊欄配置本身須要的一些maven依賴,如web,mysql connector等。點擊Generate Project下載配置好的項目zip包。
java

start

step2
若是你使用idea或者eclipse(須要安裝spring boot插件)也能夠快速生成一個項目,idea以下圖
start

step3
因爲項目比較簡單,併發量不大,直接使用界面的mybatis generator 去 https://github.com/zouzg/mybatis-generator-gui.git clone下來,maven編譯後啓動,鏈接你的數據庫就可使用它來快速生成dao層和mapper文件及model了。
generator

step4
數據庫dao層,model,mappers文件都已經生成完了,咱們應該鏈接一下數據庫試試了,Druid數據庫配置以下:

# 數據庫訪問配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@ip:port:oratest
spring.datasource.username=xxx
spring.datasource.password=xxx
# 下面爲鏈接池的補充設置,應用到上面全部數據源中
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
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
spring.datasource.logSlowSql=true
#這裏注意增長一個mappers文件的位置,否則會報錯
mybatis.mapperLocations=classpath*:mappers/*.xml

光有上面的配置還不行,還須要一個configuration配置,configuration至關於xml文件裏面的bean配置,建立的時候直接複製粘貼就好了mysql

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DruidConfig {
    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.maxActive}")
    private int maxActive;
    @Value("${spring.datasource.maxWait}")
    private int maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;
    @Value("${spring.datasource.filters}")
    private String filters;
    @Value("${spring.datasource.logSlowSql}")
    private String logSlowSql;
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("loginUsername", username);
        reg.addInitParameter("loginPassword", password);
        reg.addInitParameter("logSlowSql", logSlowSql);
        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/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }
    @Bean
    public DataSource druidDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        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);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        return datasource;
    }

}

不出意外你上面的configuration應該會飄紅,由於你沒有配置pom文件的依賴。把下面的依賴引入進去,若是你使用的是mysql的connector,就引入mysql的依賴git

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--下面是oracle的鏈接器-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>12.1.0.1-atlassian-hosted</version>
            <exclusions>
                <exclusion>
                    <groupId>cglib</groupId>
                    <artifactId>cglib</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--下面是mysql的鏈接器-->
        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

覺得上面配置結束就能夠開心的馬騮了?NONONO!還有個坑呢,主文件裏須要添加@MapperScan,參數爲你dao接口的路徑,不然就會報bean的相關異常哦!github

@MapperScan("com.netease.paygateway.dao")
@SpringBootApplication
public class PaygatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(PaygatewayApplication.class, args);
    }
}

step4
寫一個Junit測試類測一測,在main目錄的兄弟目錄test下建立一個測試類,也能夠在某個dao類直接使用ctrl+shift+T(idea),在類上右鍵新建junit(eclipse)。注意添加兩個註解,@SpringBootTest裏面的註解就是你的主類Application。web

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PaygatewayApplication.class)
public class ChargeServiceTest {

    @Autowired
    ChargeDAO chargeDAO;

    @Test
    public void getChargeVOList() {
        ChargeVOExample example = new ChargeVOExample();
        example.createCriteria().andChargeIdEqualTo("2018052415GCR30503164");
        List<ChargeVO> result = chargeDAO.selectByExample(example);
        System.out.println(result);
    }
}

Druid的精簡化配置

step1
添加依賴 Druid各版本Starterspring

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

step2
application.yml配置sql

spring:
  application:
    name: springboot-test-exam1
  datasource:
    # 使用阿里的Druid鏈接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    # 配置jdbc
    url: jdbc:mysql://localhost:3306/dbname?useSSL=false&characterEncoding=utf8
    username: root
    password: root
    # 配置鏈接池
    druid:
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置獲取鏈接等待超時的時間
      maxWait: 60000
      # 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一個鏈接在池中最小生存的時間,單位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打開PSCache,而且指定每一個鏈接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
      filters: stat,wall,log4j
      # 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      # 配置DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # 配置DruidStatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP白名單(沒有配置或者爲空,則容許全部訪問)
        allow: 127.0.0.1,192.168.163.1
        # IP黑名單 (存在共同時,deny優先於allow)
        deny: 192.168.1.73
        #  禁用HTML頁面上的「Reset All」功能
        reset-enable: false
        # 登陸名
        login-username: admin
        # 登陸密碼
        login-password: 123456

properties版本數據庫

server.port=8080
spring.application.name=test
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/databaseName?useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connectionProperties=druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,192.168.163.1
spring.datasource.druid.stat-view-servlet.deny=192.168.1.73
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=123456

step3
訪問:http://localhost:8080/druid/,登陸名:admin,密碼123456springboot

相關文章
相關標籤/搜索