Spring boot (9): spring boot uses Druid data source

Druid is a database connection pool implementation on Alibaba open source platform. It combines the advantages of C3P0, DBCP, PROXOOL and other DB pools, and adds log monitoring. It can monitor the connection of DB pool and the execution of SQL. It can be said that Druid is a DB connection pool generated for monitoring (it is said to be the best connection pool at present)

1, Dependence

To test, use the JDBC template

<!-- jdbcTemplate -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- druid Database connection pool -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.26</version>
</dependency>

<!-- mysql connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

2, Druid configuration

druid.properties

#Database settings
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/uu_core?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#--------------------------
# The following is the supplementary settings of the connection pool, which are applied to all data sources above
# Initialization size, min, Max
spring.datasource.initialSize=5
spring.datasource.minIdle=1
spring.datasource.maxActive=50
# Configure the timeout time for getting connection waiting
spring.datasource.maxWait=60000
# Configure how often to check the interval. Check the idle connections that need to be closed, in milliseconds
spring.datasource.timeBetweenEvictionRunsMillis=60000
# Configure the minimum lifetime of a connection in the pool, in milliseconds
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# Open PSCache and specify the size of PSCache on each connection
spring.datasource.poolPreparedStatements=false
#spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# Configure the filters intercepted by monitoring statistics. After the filters are removed, the monitoring interface sql cannot be counted. The 'wall' is used for the firewall
spring.datasource.filters=stat,wall,log4j
# Open mergeSql function through connectProperties property; slow SQL record
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# Merge monitoring data from multiple druiddatasources
#spring.datasource.useGlobalDataSourceStat=true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

3, Instantiate Druid Datasource

package cn.aduu.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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.PropertySource;

import javax.sql.DataSource;

/**
 * @author zh
 * @ClassName cn.aduu.config.DruidConfiguration
 * @Description
 */
@Configuration
@PropertySource(value = "classpath:druid.properties")
public class DruidConfiguration {

    @Bean(destroyMethod = "close", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    /**
     * Register a StatViewServlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidStatViewServlet(){
        //org.springframework.boot.context.embedded.ServletRegistrationBean provides class registration
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        //Add initialization parameter: initParams
        //White list:
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //IP Blacklist (deny takes precedence over allow when there is a common one): if deny is satisfied, prompt: sorry, you are not allowed to view this page
        servletRegistrationBean.addInitParameter("deny","192.168.1.73");
        //Login to view the account password of the information
        servletRegistrationBean.addInitParameter("loginUsername","admin");
        servletRegistrationBean.addInitParameter("loginPassword","123456");
        //Whether the data can be reset
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    /**
     * Register a: filterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){

        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

        //Add filter rule
        filterRegistrationBean.addUrlPatterns("/*");

        //Add formatting information that does not need to be ignored
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

4, Monitoring

Visit http://localhost:8080/druid , use the account password configured above.

5, Testing

@RestController
public class HelloController{

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("hello")
    public List<Map<String, Object>> hello() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT user,password FROM mysql.user ", new Object[]{});
        return list;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Visit localhost:8080/hello

[
    {
        "user": "root",
        "password": "*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B"
    },
    {
        "user": "root",
        "password": "*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B"
    }
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
                                <link rel="stylesheet" href="http://csdnimg.cn/release/phoenix/production/markdown_views-10f5517761.css">
                                </div>

Reproduced from: http://blog.csdn.net/saytime

Keywords: Spring Druid MySQL SQL

Added by hpg4815 on Sun, 03 May 2020 00:27:55 +0300