Spring Boot2 integrates with druid data sources

Properties does not match the poM dependencies with the application. Properties does not match the POM dependencies with the application. Properties does not match the POM dependencies with the application

Project Example GitHub github.com/ZhangXiaoix…

Resist to put resources in CSDN need points to download (Baidu web disk, code cloud,GitHub can be, but you will not need points, conscience ha)

New ServletRegistrationBean(new StatViewServlet(), “/druid/*”); This code error, please refer to

* * * * blog.csdn.net/q343509740/…

 

1: POM dependencies (note how integration Druid connection pools are written)

<! --mysql--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <! Alibaba </groupId> <artifactId> Druid </artifactId> <version>1.1.4</version> </dependency>Copy the code

2:properties Configuration file (yml format is not write, principle), mainly pay attention to the final configuration, I temporarily comment # spring. The datasource. Filters = stat, wall, log4j2 this configuration, the first is to configure it need to introduce the corresponding dependent, and spring The default logging dependency used by Boot2 is Logback, so we need to remove that dependency and introduce log4j2. (It is ok to introduce log4j2, but log4j2 is an upgrade of log4J and better than the Logback recommended by Spring Boot2, so we had better go with the flow.)

# configure basic database connection information for the spring. The datasource. Url = JDBC: mysql: / / localhost/test spring. The datasource. The username = root spring.datasource.password=1234 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ### Data source category of alibaba DruidDataSource spring. The datasource. Type = com. Alibaba. Druid. Pool. DruidDataSource size # # # is initialized, the smallest, Largest spring. The datasource. Initial - size = 10. Spring datasource. Min - idle = 8 spring. The datasource. The Max - idle = 8 # maximum number of connection pool Spring.datasource. Max-active =20 ### configure how often to check for idle connections that need to be closed, Unit is ms spring. The datasource. MinEvictableIdleTimeMillis = 300000 # to obtain maximum wait time when connections, unit of milliseconds. After configuration maxWait, enabled by default fair lock, concurrent efficiency will decline, if you need can be configured useUnfairLock attribute to true use a fair lock spring. The datasource. MaxWait = 60000 # has two meanings: #1) Destroy the connection interval Detailed description see testWhileIdle attribute of spring. The datasource. TimeBetweenEvictionRunsMillis = 60000 # is used to test for a valid SQL connection, the requirement is a query. TestOnBorrow, testOnReturn, and testWhileIdle will not function if validationQuery is null. Pspring. The datasource. ValidationQuery = SELECT 1 FROM DUAL # suggested configuration is true, do not affect performance, and ensure safety. Apply for connection, if free time is more than timeBetweenEvictionRunsMillis, performing validationQuery test connection is valid. Spring. The datasource. TestWhileIdle = true # is valid when applying for connection of performing validationQuery test connections, the (true) this configuration will degrade performance. Return spring. The datasource. TestOnBorrow = false # connection when performing validationQuery test connection is valid, Do this configuration will lower performance spring. The datasource. TestOnReturn = false # whether cache preparedStatement, namely PSCache. PSCache provides a huge performance boost for databases that support cursors, such as Oracle. You are advised to disable this function in mysql. Spring. The datasource. PoolPreparedStatements = true spring. The datasource. MaxPoolPreparedStatementPerConnectionSize = 20 # attribute types are string, Configure an alias for an extension plug-in. Common plug-ins include: Monitoring statistics with the filter: stat logging with the filter: log4j2 defense SQL injection filter: wall spring. The datasource. The filters = stat, wall, log4j2 spring.datasource.connectionPropertie=druid.stat.mergeSql=true; druid.stat.slowSqlMillis=5000Copy the code

3: Write the data source set class (I give a reference class)



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.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 org.springframework.stereotype.Component;

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

@Configuration
public class DruidConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

    private static final String DB_PREFIX = "spring.datasource";

    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单(我下面注释了,你也可以单独写一堆类似的白名单)
//        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP黑名单(共同存在时,deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    //解决 spring.datasource.filters=stat,wall,log4j 无法正常注册进去
    @Component
    @ConfigurationProperties(prefix = DB_PREFIX)
    class IDataSourceProperties {
        private String url;
        private String username;
        private String password;
        private String driverClassName;
        private int initialSize;
        private int minIdle;
        private int maxActive;
        private int maxWait;
        private int timeBetweenEvictionRunsMillis;
        private int minEvictableIdleTimeMillis;
        private String validationQuery;
        private boolean testWhileIdle;
        private boolean testOnBorrow;
        private boolean testOnReturn;
        private boolean poolPreparedStatements;
        private int maxPoolPreparedStatementPerConnectionSize;
        private String filters;
        private String connectionProperties;

        @Bean     //声明其为Bean实例
        @Primary  //在同样的DataSource中,首先使用被标注的DataSource
        public DataSource dataSource() {
            DruidDataSource datasource = new DruidDataSource();
            datasource.setUrl(url);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);

            //configuration
            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);
            datasource.setPoolPreparedStatements(poolPreparedStatements);
            datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            try {
                datasource.setFilters(filters);
            } catch (SQLException e) {
                System.err.println("druid configuration initialization filter: " + e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }

        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 int getInitialSize() {
            return initialSize;
        }

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

        public int getMinIdle() {
            return minIdle;
        }

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

        public int getMaxActive() {
            return maxActive;
        }

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

        public int getMaxWait() {
            return maxWait;
        }

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

        public int getTimeBetweenEvictionRunsMillis() {
            return timeBetweenEvictionRunsMillis;
        }

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

        public int getMinEvictableIdleTimeMillis() {
            return minEvictableIdleTimeMillis;
        }

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

        public String getValidationQuery() {
            return validationQuery;
        }

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

        public boolean isTestWhileIdle() {
            return testWhileIdle;
        }

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

        public boolean isTestOnBorrow() {
            return testOnBorrow;
        }

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

        public boolean isTestOnReturn() {
            return testOnReturn;
        }

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

        public boolean isPoolPreparedStatements() {
            return poolPreparedStatements;
        }

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

        public int getMaxPoolPreparedStatementPerConnectionSize() {
            return maxPoolPreparedStatementPerConnectionSize;
        }

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

        public String getFilters() {
            return filters;
        }

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

        public String getConnectionProperties() {
            return connectionProperties;
        }

        public void setConnectionProperties(String connectionProperties) {
            this.connectionProperties = connectionProperties;
        }
    }

}
Copy the code

Refer to my file structure (I have configured an extra log4j2 dependency, you can also not configure it for the moment, here only for reference)

4: test (the account password is admin, the previous configuration class has written)

In the browser address bar, type in (funny, I don’t know why some address bar type in one of the addresses, the address bar shows up with a lot of druids)

Visit the druid connection 1 or visit the druid connection 2 http://localhost:8080/druid/login.html or http://localhost:8080/druid/index.html http://localhost:8080/Copy the code

 

Log in

5: Another way by the way (actually should not be called another way, is slightly different configuration writing)

For example, pom

<! <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> The < version > 1.1.10 < / version > < / dependency >Copy the code

In the configuration file

## initialize size, minimum, Largest spring. The datasource. Initial - size = 10 # note have a plenty of spring. The datasource. The druid. The initial - size = 10 # still have a plenty of attention spring.datasource.druid.initialSize=10 # config file name = "config file name" # config file name = "config file name" # config file name = "config file name" # config file name = "config file name" # config file name = "config file name" # config file name = "config file nameCopy the code

6: Spring Boot 2 configuration Log4j2 Blog to be written

No pressing him at the momentCopy the code