1. 程式人生 > >spring boot整合mybatis -配置 druid 資料來源

spring boot整合mybatis -配置 druid 資料來源

druid 資料庫連線池是由阿里提供,由於其效能很高並且提供了強大的監控功能,所以被越來越多的應用。

第一次配置,很簡單。也沒有花太多時間,最坑的是 druid 監控的配置處理時:
# 這裡一定要配置為 "/druid/*",而不是"/druid",瀏覽器會報錯404!
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid/*"); 
                #這裡一定要配置為 "/druid/*",如果是"/druid",瀏覽器會報錯404!

第一步 配置pom.xml檔案

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

同時配置 mybatis 啟動包 和 mysql 連線包

		<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>
            <scope>runtime</scope>
        </dependency>
        <!--日誌配置 將資料庫SQL執行打印出來,還需要新增一個配置檔案 logback-spring.xml  start -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
         <!--日誌配置 將資料庫SQL執行打印出來,還需要新增一個配置檔案 logback-spring.xml  end-->

第二步 配置application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 配合Druid監控的過濾配置filters ,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j 

同時配置 mybatis

spring.datasource.url = jdbc:mysql://**資料庫ip**:3306/mldn?useUnicode=true&amp;characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=50
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=true
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=false  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 
# 配合Druid監控的過濾配置filters ,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j 
# connectProperties
spring.datasources.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# Mybatis配置
# Mybatis所有操作類的別名所在包
mybatis.typeAliasesPackage=com.example.demo.bean
# Mybatis所有的對映檔案
mybatis.mapperLocations=classpath:mapper/**/*.xml
# Mybatis配置檔案所在路徑
mybatis.config-location=classpath:mybatis-config.xml

當然還要有Mybatis配置檔案:src\main\resources\mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-mybatis.org//DTD Config 3.0//EN" "http://mybatis.org.dtd/mybatis-3-config.dtd">
<configuration>
 	<settings>
        <!-- 列印查詢語句 -->
        <!--<setting name="logImpl" value="STDOUT_LOGGING" />-->
        <setting name="logImpl" value="SLF4J" />
    </settings>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>

logback配置檔案:src\main\resources\logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
	<!-- 儘量別用絕對路徑,如果帶引數不同容器路徑解釋可能不同 -->
	<property name="LOG_HOME" value="../logs" />
	<springProperty scope="context" name="logLevel" source="log.level"/>
	<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</layout>
	</appender>

	<!-- 按照每天生成日誌檔案 -->
	<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>${LOG_HOME}/CcxDecision_%d{yyyy-MM-dd}.log</FileNamePattern>
			<MaxHistory>180</MaxHistory>
		</rollingPolicy>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</layout>
	</appender>

	<!--設定具體包的日誌級別-->
	<springProfile name="dev,product">
		**<logger name="com.example.demo" level="debug" />** <!-- 配置自己專案 -->
		<logger name="org.springframework.web" level="debug"/>
		<logger name="io.lettuce.core.RedisClient" level="debug" />
		<logger name="org.apache.http.wire" level="debug" />
		<logger name="com.mycompany.myapp.mapper.MyMapper" level="DEBUG"/>
	</springProfile>

	<root level="${logLevel}"> <!-- root將級別為“INFO”及大於“INFO”的日誌資訊交給已經配置好的名為“Console”的appender處理,“Console”appender將資訊列印到Console; -->
		<appender-ref ref="Console" /> <!-- 標識這個appender將會新增到這個logger -->
		<appender-ref ref="FILE" />
	</root>
</configuration>

最終在我們專案logs下可以看到日誌檔案 在這裡插入圖片描述

第三步

新增一個 druid 配置類,設定 DruidDataSource。 DruidConfig.java

package com.example.demo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DruidConfig {
    // 主要實現WEB監控的配置處理
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid"); //進行druid監控的配置處理操作
        servletRegistrationBean.addInitParameter("allow",
                "127.0.0.1,10.0.5.58"); // 白名單
        servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名單
        servletRegistrationBean.addInitParameter("loginUsername", "druid"); // druid的使用者名稱
        servletRegistrationBean.addInitParameter("loginPassword", "druid"); // druid的密碼
        servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置資料來源
        return servletRegistrationBean;
    }

    // 主要實現檔案監控的配置處理
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*"); // 所有請求進行監控處理
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");// 不監控的格式
        return filterRegistrationBean;
    }
    // 將所有字首為spring.datasource下的配置項都載入到DataSource中
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}

注意:非常關鍵的監控配置:

ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid/*"); 
                #這裡一定要配置為 "/druid/*",如果是"/druid",瀏覽器會報錯404!

第四步 驗證

輸入地址:http://localhost/druid/login.html 在這裡插入圖片描述 登陸成功,可以很清晰的看到我剛剛執行的SQL:(自己寫一個查詢方法,進入druid監控前,先執行幾次) 在這裡插入圖片描述