Spring Boot tutorial four: Using Druid and Monitoring configuration

Source: Internet
Author: User
Tags connection pooling html page reset spring boot tutorial log4j

The

Druid is the best database connection pool in the Java language and provides powerful monitoring and scaling capabilities.
the industry compared Druid and HIKARICP, although HIKARICP performance is higher than Druid, but because Druid includes many dimensions of statistical and analytical functions, so this is why everyone chooses to use it.
The following describes how to configure using Druid in Springboot
1: Modify the Pom file to add dependencies:

<dependencies> <!--exclude the default log frame--<dependency> <groupid>org.springframewo Rk.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> <exclusion
                    S> <exclusion> <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupid>org.springframe Work.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <scope& Gt;test</scope> </dependency> <!--log4j--> <dependency> <g Roupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-log4j</artifactid&
            Gt <version>1.3.8.release</version> </dependency> <dependency> <groupid>co M.alibaba</groupid> <artifactId>druid</artifactId> <version>1.0.18</ver Sion> </dependency> <!--database driver--<dependency> <groupid>mysql</ Groupid> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</ver Sion> </dependency> </dependencies>

2: Add the appropriate data source configuration in the configuration file:

# Server settings (serverproperties) #端口 server.port=8082 server.address=127.0.0.1 #server. sessiontimeout=30 #访问路径名称
Server.contextpath=/boot # Database Access configuration # Primary data source, default Spring.datasource.type=com.alibaba.druid.pool.druiddatasource
Spring.datasource.driverclassname=com.mysql.jdbc.driver Spring.datasource.url=jdbc:mysql://localhost:3306/test
Spring.datasource.username=root spring.datasource.password=123456 # Below are supplemental settings for connection pooling, applied to all data sources above # initialization size, MIN, max
spring.datasource.initialsize=5 spring.datasource.minidle=5 spring.datasource.maxactive=20 # Configure the time to get the connection wait timeout spring.datasource.maxwait=60000 # How long does the configuration interval take to detect idle connections that need to be closed, in milliseconds spring.datasource.timeBetweenEvictionRunsMillis
=60000 # Configures the minimum time for a connection to survive in a pool, in milliseconds spring.datasource.minevictableidletimemillis=300000
Spring.datasource.validationquery=select 1 fromdual 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=true Spring.dataSOURCE.MAXPOOLPREPAREDSTATEMENTPERCONNECTIONSIZE=20 # Configure monitoring Statistics intercept filters, remove post-monitoring interface SQL cannot be counted, ' wall ' for firewalls
SPRING.DATASOURCE.FILTERS=STAT,WALL,LOG4J # Connectproperties property to open mergesql function; slow SQL record spring.datasource.connectionproperties=druid.stat.mergesql=true;druid.stat.slowsqlmillis=5000 # Consolidate monitoring data #spring for multiple druiddatasource. datasource.useglobaldatasourcestat=true

There are two ways to configure monitoring, one: Configure Servlet,filter, and finally, in the Ingress class, you need to add @servletcomponentscan annotations (Spring can scan to our own servlet and filter)
code as follows:

@WebServlet (urlpatterns= "/druid/*", initparams={@WebInitParam (NA Me= "Allow", value= "192.168.1.72,127.0.0.1"),//IP whitelist (no configuration or null, all access is allowed) @WebInitParam (name= "de NY ", value=" 192.168.1.73 "),//IP blacklist (when common, deny takes precedence over Allow) @WebInitParam (name=" Loginusername ", VA
                             Lue= "admin"),//user name @WebInitParam (name= "Loginpassword", value= "123456"),//password @WebInitParam (name= "resetenable", value= "false")//disable "Reset all" function on HTML page) Publicclass D

Ruidstatviewservlet extendsstatviewservlet{privatestatic Finallong serialversionuid = 1L;
 }/** *druid filter.
                            * @author Administrator * */@WebFilter (filtername= "Druidwebstatfilter", urlpatterns= "/*", initparams={
        @WebInitParam (name= "exclusions", value= "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//Ignore Resources }) Publicclass DruidstatfiLter extends webstatfilter{} 

Then, after starting the project, Access http://127.0.0.1:8082/boot/druid/login.html,

Mode two, relatively simple:

/** * @author Shuyu.wang * @version V1.0 * @ClassName: Druidconfiguration * @Description: *druid configuration. There is no need to add annotations in this way: @Ser Vletcomponentscan * @date November 23, 2017 pm 2:35:55 * * @Configuration public class Druidconfig {private Logger Logger
    = Logger.getlogger (Druidconfig.class); /** * Register a statviewservlet * * @return * * @Bean public Servletregistrationbean Druidstatviewser
        Vle2 () {///Org.springframework.boot.context.embedded.ServletRegistrationBean provides the registration of the class. Servletregistrationbean Servletregistrationbean = new Servletregistrationbean (new Statviewservlet (), "/dru

        id2/* ");
        Add initialization parameters: InitParams//Whitelist: Servletregistrationbean.addinitparameter ("Allow", "127.0.0.1");
        IP blacklist (when common, deny takes precedence over allow): If Deny is satisfied: Sorry, you is not the permitted to//view this page.
        Servletregistrationbean.addinitparameter ("Deny", "192.168.1.73");
        Log in to view the account password of the information. ServletregistrationBean.addinitparameter ("Loginusername", "admin2");
        Servletregistrationbean.addinitparameter ("Loginpassword", "123456");
        Whether the data can be reset.
        Servletregistrationbean.addinitparameter ("Resetenable", "false");
    return Servletregistrationbean; }/** * Register one: Filterregistrationbean * * @return * * @Bean public Filterregistrationbean Dr UidStatFilter2 () {Filterregistrationbean Filterregistrationbean = new Filterregistrationbean (new Webstatfilter ())
        ;
        Add filter rules.
        Filterregistrationbean.addurlpatterns ("/*");
        Add formatting information that you do not need to ignore.
        Filterregistrationbean.addinitparameter ("Exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
    return Filterregistrationbean;
     }/** * Register Datasouce, here is just a simple example, just inject some parameters, other self-injected. * * @param driver * @param URL * @param username * @param password * @param maxactive * @ret URN */@Bean public DataSource DruiddaTasource (@Value ("${spring.datasource.driverclassname}") String driver, @Value ("${spr
                                      Ing.datasource.url} ") string URL, @Value (" ${spring.datasource.username} ") string username, @Value ("${spring.datasource.password}") String password, @Value ("${spring.dat
        Asource.maxactive} ") int maxactive) {Druiddatasource Druiddatasource = new Druiddatasource ();
        Druiddatasource.setdriverclassname (driver);
        Druiddatasource.seturl (URL);
        Druiddatasource.setusername (username);
        Druiddatasource.setpassword (password);
        Druiddatasource.setmaxactive (maxactive);
        Logger.info ("Druidconfiguration.druiddatasource (), url=" + URL + ", username=" + Username + ", password=" + password);
        try {druiddatasource.setfilters ("stat, Wall");
        } catch (SQLException e) {e.printstacktrace (); } return DruiddatasourCe
 }
}

Launch the app to access: Http://127.0.0.1:8082/boot/druid2/login.html Enter your account and password: admin2/123456 can access it.

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.