preface
Druid database connection pool this section describes the Druid database connection pool.
There are two kinds of database connection pool in my knowledge store ->C3P0, DBCP, but now it seems not enough. Most of the books I have read also introduce these two kinds of database connection pools, and my own Demo also uses C3P0. But now it seems that neither of these is enough. The industry is growing so fast
I don’t have to type the code above, but it’s all comments from some enthusiastic developers. It’s because of their comments that I’m motivated to learn better things, and I hope you can give me more Pointers
As a result, I spent a little time learning about Druid database connection pooling… If there is something wrong, point to it
The Druid database connection pool is owned by Ali, so the documentation is available in Chinese, so learning English is less of a headache.
Druid introduction
Druid has two common uses:
- Replace C3P0, DBCP database connection pool (for better performance)
- Provides a monitoring page to monitor application connection pools in real time
Use Druid as a database connection pool and use the real-time monitoring application to get started
Build the Druid environment
SpringBoot and SpringData JPA are used to build a Druid Demo
2.1 introduction of pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
</dependencies>
Copy the code
2.2Druid Default configuration
Configure data source information (Druid), and JPA related configuration ~
Primary data source, The default spring. The datasource. Type = com. Alibaba. Druid. Pool. DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/druid Spring. The datasource. The username = root spring. The datasource. The password = root # below to replenish the connection pool Settings, applied to the above size # of all the data source is initialized, the smallest, Spring. The biggest datasource. InitialSize = 5 spring. The datasource. MinIdle = 5 spring. The datasource. MaxActive = 20 # configuration for connecting wait for timeout time Spring. The datasource. MaxWait = 60000 # configure how long is the interval to conduct a test, testing needs to be closed free connection, Unit is ms spring. The datasource. TimeBetweenEvictionRunsMillis = 60000 # to configure a connection in the pool minimum survival time, Unit is ms spring. The datasource. MinEvictableIdleTimeMillis = 300000 spring. The datasource. The validationQuery = SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # Open the PSCache, And the size of the specified on each connection PSCache spring. The datasource. PoolPreparedStatements = true Spring. The datasource. MaxPoolPreparedStatementPerConnectionSize = 20 # configuration monitoring statistics of intercepting filters, remove the monitor interface after SQL is unable to statistics, 'wall' firewall used in spring. The datasource. Filters = stat, wall, log4j # by connectProperties attribute to open mergeSql function; Slow SQL record spring. The datasource. ConnectionProperties = druid. Stat. MergeSql = true; Druid. Stat. Consolidate multiple DruidDataSource slowSqlMillis = 5000 # # the monitoring data of spring. The datasource. UseGlobalDataSourceStat = true # JPA configuration spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=trueCopy the code
For more information, see the official documentation, but this is generally enough.
2.3 Configuring monitoring
Druid uses the Filter-chain extension. If you want to enable StatFilter, configure StatFilter
Configure druid data source status monitoring with an interceptor and a Servlet
package com.example.demo;
/**
* Created by ozc on 2018/3/26.
*
* @author ozc
* @version1.0 * /
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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;
/** * druid configuration. * <p>@ServletComponentScan
*
* @author Administrator
*/
@Configuration
public class DruidConfiguration {
/** * Register a StatViewServlet **@return* /
@Bean
public ServletRegistrationBean DruidStatViewServle2(a) {
/ / org. Springframework. Boot. Context. Embedded. ServletRegistrationBean provide for registration of a class.
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// Add the initialization parameter initParams
// Whitelist:
servletRegistrationBean.addInitParameter("allow"."127.0.0.1");
//IP blacklist (if there is a common, deny precedence over allow) :Sorry, you are not permitted to view this page
servletRegistrationBean.addInitParameter("deny"."192.168.1.73");
// Password for logging in to view information.
servletRegistrationBean.addInitParameter("loginUsername"."admin2");
servletRegistrationBean.addInitParameter("loginPassword"."123456");
// Whether data can be reset.
servletRegistrationBean.addInitParameter("resetEnable"."false");
return servletRegistrationBean;
}
/** * Register a: filterRegistrationBean **@return* /
@Bean
public FilterRegistrationBean druidStatFilter2(a) {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// Add a filter rule.
filterRegistrationBean.addUrlPatterns("/ *");
// Add format information that does not need to be ignored.
filterRegistrationBean.addInitParameter("exclusions"."*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
returnfilterRegistrationBean; }}Copy the code
JPA 2.4 test
POJO:
@Entity
public class User implements Serializable {
/** * serialVersionUID. */
private static final long serialVersionUID = 1L;
/** * primary key. */
@Id
@GeneratedValue
private String id;
/** * User name. */
private String userName = "";
/** * Mobile phone number. */
private String mobileNo = "";
/** * email address. */
private String email = "";
/** * Password. */
private String password = "";
/** * User type. */
private Integer userType = 0;
/** * Registration time. */
private Date registerTime = new Date();
/** * location. */
private String region = "";
/** * valid 0 Valid 1 Invalid */
private Integer validity = 0;
/** * avatar. */
private String headPortrait = "";
}
Copy the code
Controller:
@RestController
public class UserController {
@Autowired
private UserRepos userRepos;
@RequestMapping(value="saveUser")
public User saveUser(a){
return userRepos.save(new User());
}
@RequestMapping(value="/findByUserName")
public List<User> findByUserName(String userName){
return userRepos.findByUserName(userName);
}
@RequestMapping(value="findByUserNameLike")
public List<User> findByUserNameLkie(String userName){
return userRepos.findByUserNameLike(userName);
}
@RequestMapping(value="findByPage")
public Page<User> findByPage(Integer userType){
return userRepos.findByUserType(userType, new PageRequest(1.5)); }}Copy the code
Repository:
public interface UserRepos extends JpaRepository<User.String> {
/** * query ** by user name equality@paramUserName userName *@return* /
List<User> findByUserName(String userName);
/** * query ** by name like@paramUserName userName *@return* /
List<User> findByUserNameLike(String userName);
/** * Query ** by user name and mobile phone number@paramUserName userName *@paramMobileNo Mobile number *@return* /
User findByUserNameAndMobileNo(String userName, String mobileNo);
/** ** query ** according to user type@paramUserType userType *@param pageable
* @return* /
Page<User> findByUserType(Integer userType, Pageable pageable);
/** * Sort query ** by user name@paramUserName userName *@param sort
* @return* /
List<User> findByUserName(String userName, Sort sort);
}
Copy the code
On the page visit: http://localhost:8080/findByUserName? userName=Java3y
Results:
Three, the last
This article is just a quick primer on Druid, an excellent open source database connection pooling framework. See the GitHub documentation for more information.
References:
- Document page
- GitHub documentation problem
- Ali Druid learning, known as the best database connection pool
- Common database connection pools (DBCP, C3P0, and Druid) are described
- SpringBoot learning: Integrate MyBatis and use Druid connection pool
- SpringBoot: SpringBoot uses Druid and monitors configuration
- Spring Boot Druid Data source configuration
Update: Reminded by comments: Druid uses properties to configure data connection pool properties in SpringBoot.
Reference: https://blog.csdn.net/lijunfan_rh/article/details/53665492
Just add a Durid configuration class and POM adds the log coordinates:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Copy the code
If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y