Springboot:spring Boot uses Druid and monitoring to configure __ database connection pool

Source: Internet
Author: User
Tags connection pooling log4j
Druid is the best database connection pool in the Java language and can provide powerful monitoring and extension capabilities.
The default data source for Spring boot is: Org.apache.tomcat.jdbc.pool.DataSource


How to configure the use of Druid in spring Boot, the overall step:
(1)--druid Simple Introduction, concrete reader net;
(2)--Configure Druid Dependency pack in Pom.xml;
(3)--Configure Application.properties to join the database source type and other parameters;
(4)--Write Druid servlet and filter to provide monitoring page access;
(5)--input address for testing;

Specific:
(1) Add Maven dependencies (or jar packs)
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactid>druid</artifactid >
	<version>1.0.18</version>
</dependency>
(2), configuring data source related information (application.properties)
# Database Access configuration # Main data source, default Spring.datasource.type=com.alibaba.druid.pool.druiddatasource Spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:3306/
Test Spring.datasource.username=root spring.datasource.password=123456 # The following supplemental settings for connection pooling apply to all data sources above # initialization size, MIN, max
Spring.datasource.initialsize=5 spring.datasource.minidle=5 spring.datasource.maxactive=20 # Configuration Gets the time the connection waits to timeout spring.datasource.maxwait=60000 # Configure how often the interval is detected to detect idle connections that need to be closed, in milliseconds spring.datasource.timeBetweenEvictionRunsMillis
=60000 # Configures the minimum time that a connection is to survive 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 # Opens Pscache and specifies the size of pscache on each connection Spring.datasource.poolpreparedstatements=true spring.datasource.maxpoolpreparedstatementperconnectionsize=20 #
Configure the monitoring of statistical interception of filters, remove the monitoring interface after the SQL can not be counted, ' wall ' for firewall spring.datasource.filters=stat,wall,log4j# Open Mergesql function by connectproperties property; slow SQL record spring.datasource.connectionproperties=druid.stat.mergesql=true;   druid.stat.slowsqlmillis=5000 # Merge multiple Druiddatasource monitoring data #spring. datasource.useglobaldatasourcestat=true

(3) Configure the Monitoring statistics function, register the servlet with code
/** * Register a Statviewservlet * @return * * @Bean public Servletregistrationbean Druidstatviewservle () {
        Org.springframework.boot.context.embedded.ServletRegistrationBean provides the registration of the class.
        Servletregistrationbean Servletregistrationbean = new Servletregistrationbean (new Statviewservlet (), "/druid/*");
        Add initialization parameters: InitParams//Whitelist: Servletregistrationbean.addinitparameter ("Allow", "127.0.0.1");
        IP blacklist (when in common, the deny takes precedence over allow): If the Deny is satisfied, prompt: Sorry, you are not permitted to view this page.
        Servletregistrationbean.addinitparameter ("Deny", "192.168.1.11");
        Login to view information on the account password.
        Servletregistrationbean.addinitparameter ("Loginusername", "admin");
        Servletregistrationbean.addinitparameter ("Loginpassword", "123456");
        Whether the data can be reset.
        Servletregistrationbean.addinitparameter ("Resetenable", "false");
    return Servletregistrationbean;
    /** * Register One: Filterregistrationbean * @return * *@Bean public Filterregistrationbean Druidstatfilter () {Filterregistrationbean Filterregistrationbean = new Fil
        Terregistrationbean (New Webstatfilter ());
        Add a filter rule.
        Filterregistrationbean.addurlpatterns ("/*");
        Add formatting information that you do not need to ignore.
        Filterregistrationbean.addinitparameter ("Exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return Filterregistrationbean; }

/** * Load Druid database connection pool * @return return Druiddatasource Object * * Private Druiddatasource Cfgdatasource () {D
        Ruiddatasource Druidds = new Druiddatasource ();
        String initialsize = Cfgservice (). get (Dbconstants.duridinitialsize);
        String Minidle = Cfgservice (). get (Dbconstants.duridminidle);
        String maxactive = Cfgservice (). get (Dbconstants.duridmaxactive);
        String maxwait = Cfgservice (). get (dbconstants.duridmaxwait);
        String Timebetweenevictionrunsmillis = Cfgservice (). get (Dbconstants.duridtimebetweenevictionrunsmillis);
        String Minevictableidletimemillis = Cfgservice (). get (Dbconstants.duridminevictableidletimemillis);
        String validationquery = Cfgservice (). get (Dbconstants.duridvalidationquery);
        String Testwhileidle = Cfgservice (). get (Dbconstants.duridtestwhileidle);
        String Testonborrow = Cfgservice (). get (Dbconstants.duridtestonborrow); String Testonreturn = Cfgservice (). Get (Dbconstants.duridtestonreturn);
        String poolpreparedstatements = Cfgservice (). get (Dbconstants.duridpoolpreparedstatements); String maxpoolpreparedstatementperconnectionsize = Cfgservice (). Get (
        Dbconstants.duridmaxpoolpreparedstatementperconnectionsize);
        String removeabandoned = Cfgservice (). get (dbconstants.removeabandoned);
        String removeabandonedtimeout = Cfgservice (). get (Dbconstants.removeabandonedtimeout);
        String logabandoned = Cfgservice (). get (dbconstants.logabandoned); try {//<!--Configure initialization size, MIN, max--> druidds.setinitialsize (integer.parseint stringutils.isempty (i nitialsize)? "
            1 ": initialsize)); Druidds.setminidle (Integer.parseint) (Stringutils.isempty (minidle)?
            1 ": Minidle)); Druidds.setmaxactive (Integer.parseint) (Stringutils.isempty (maxactive)?
            ": maxactive)"); <!--Configure the time to get the connection wait timeout--> druidds.setmaxwait (Long.parselong stringutils.isempty (maxwait)?
            60000 ": maxwait)); <!--configuration RoomHow often does it take a test to detect an idle connection that needs to be closed, in milliseconds--> druidds.settimebetweenevictionrunsmillis (Long.parselong stringutils.isempt Y (timebetweenevictionrunsmillis)? "
            60000 ": Timebetweenevictionrunsmillis)); <!--Configure the minimum time that a connection is to survive in the pool, in milliseconds--> druidds.setminevictableidletimemillis (Long.parselong stringutils.isemp Ty (minevictableidletimemillis)? "
            300000 ": Minevictableidletimemillis)); Druidds.setvalidationquery (Stringutils.isempty (validationquery)? "
            Select ' x ': Validationquery); Druidds.settestwhileidle (Boolean.parseboolean) (Stringutils.isempty (testwhileidle)?
            True ": Testwhileidle)); Druidds.settestonborrow (Boolean.parseboolean) (Stringutils.isempty (Testonborrow)?
            False ": Testonborrow)); Druidds.settestonreturn (Boolean.parseboolean) (Stringutils.isempty (Testonreturn)?
            False ": Testonreturn)); <!--open Pscache and specify the size of Pscache on each connection--> druidds.setpoolpreparedstatements Boolean.parseboolean (stringut Ils.isempty (poolpreparedstatements)? "
            True ":p oolpreparedstatements)); Druidds.setmaxpoolpreparedstatementperconnectionsize (Integer.parseint (Stringutils.isempty) ( maxpoolpreparedstatementperconnectionsize)? "
            ": Maxpoolpreparedstatementperconnectionsize)"); Druidds.setremoveabandoned (Boolean.parseboolean) (Stringutils.isempty (removeabandoned)?
            True ": removeabandoned)); Druidds.setremoveabandonedtimeout (Integer.parseint) (Stringutils.isempty (removeabandonedtimeout)?
            180 ": removeabandonedtimeout)); Druidds.setlogabandoned (Boolean.parseboolean) (Stringutils.isempty (logabandoned)?
            True ": logabandoned));
        <!--configuration Monitor the filters of statistical interception, after removing the monitor interface SQL can not count--> druidds.setfilters ("stat,log4j");
        catch (SQLException e) {logutils.warn ("Load Druid data Source Monitor Service exception:" + E.getmessage (), E);
    return druidds; }

(4) Access Verification

Start an application to access: Http://127.0.0.1:8080/druid

Enter account and password: admin/123456 can be accessed, as shown below:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.