Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A preliminary understanding of the open source framework Druid for database connection pooling

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Druid is an open source framework of Alibaba's database connection pooling. To be exact, it not only includes database connection pooling, but also provides powerful monitoring and expansion functions. This article is only a snoop on Druid without the Spring framework, using the latest version of druid1.0.26 github address: https://github.com/alibaba/druid.

Before we start, let's talk about why we don't use Spring to use Druid connection pooling. The reason is that Druid can be used with only one configuration datasource in the configuration file of the Spring framework. So what exactly did Spring do to this datasource data source when it was configured? How exactly does it implement this datasource data source? If you don't know the other but know one, you are really just a brick lifter.

Let's get started. First of all, let's take a look at the structure of the project package.

There are also two jar to introduce, one is druid, the other is mysql-connector.

We first implement the DBPoolConnection class in the util package, which is used to create a database connection pool singleton and to return a database connection. Why do database connection pooling need singletons? The reason is simple. We can imagine that in a web application, there may be multiple requests at the same time. What's the point of creating a database connection pool for each request? It should be that no matter how many concurrent requests there are, there should be only one database connection pool in which one database connection should be created for each request.

1 package util; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.InputStream; 6 import java.sql.SQLException; 7 import java.util.Properties; 8 9 import com.alibaba.druid.pool.DruidDataSource;10 import com.alibaba.druid.pool.DruidDataSourceFactory;11 import com.alibaba.druid.pool.DruidPooledConnection 12 13 / * * 14 * to implement singleton mode, ensure that there is only one global database connection pool 15 * @ author ylf16 * 17 * October 21, 2016 18 * / 19 public class DBPoolConnection {20 private static DBPoolConnection dbPoolConnection = null;21 private static DruidDataSource druidDataSource = null;22 23 static {24 Properties properties = loadPropertiesFile ("db_server.properties"); 25 try {26 druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource (properties) / / DruidDataSrouce Factory Mode 27} catch (Exception e) {28 e.printStackTrace (); 29} 30} 31 32 / * * 33 * Database connection Pool Singleton 34 * @ return35 * / 36 public static synchronized DBPoolConnection getInstance () {37 if (null = = dbPoolConnection) {38 dbPoolConnection = new DBPoolConnection (); 39} 40 return dbPoolConnection 41} 42 43 / * * 44 * return druid database connection 45 * @ return46 * @ throws SQLException47 * / 48 public DruidPooledConnection getConnection () throws SQLException {49 return druidDataSource.getConnection () 50} 51 / * * 52 * @ param string configuration file name 53 * @ return Properties object 54 * / 55 private static Properties loadPropertiesFile (String fullFile) {56 String webRootPath = null;57 if (null = = fullFile | | fullFile.equals (")) {58 throw new IllegalArgumentException (" Properties file path can not be null "+ fullFile) 59} 60 webRootPath = DBPoolConnection.class.getClassLoader (). GetResource ("). GetPath (); 61 webRootPath = new File (webRootPath). GetParent (); 62 InputStream inputStream = null;63 Properties p = null;64 try {65 inputStream = new FileInputStream (new File (webRootPath + File.separator + fullFile)); 66 p = new Properties (); 67 p.load (inputStream) 68} catch (Exception e) {69 e.printStackTrace (); 70} finally {71 try {72 if (null! = inputStream) {73 inputStream.close (); 74} 75} catch (Exception e) {76 e.printStackTrace () 77} 78} 79 80 return pten 81} 82 83}

When line 26 instantiates a DruidDataSource, we can create a DruidDataSource instance of the DruidDataSourceFactory we provide through the Druid framework, and the factory pattern gives us great convenience.

The line 36 getInstance method creates a database connection pool instance for us, where the singleton pattern is used, where we can use the synchronized method to lock (lazy load) getInstance to achieve thread safety, and we can also use frequent loading to achieve thread safety, that is, remove the synchronized keyword, delete line 37-39, and change line 20 to private static DBPoolConnection dbPoolConnection = new DBPoolConnection (). These two ways have their own advantages and disadvantages, lazy loading advantage is "used to instantiate", the disadvantage is "synchronized keyword locking method slightly larger granularity, using synchronization to achieve thread safety will bring additional overhead", and the advantage of diligent loading is "do not use synchronization to achieve thread safety, save the extra overhead brought by the synchronization mechanism", the disadvantage is "not used will be instantiated". As for how to choose, according to the actual situation. Here are two previous blog posts on singleton pattern, "Singleton pattern" and "Thread Safety issues of Singleton pattern".

The loadPropertiesFile method in line 55 is the load of the properties configuration file.

What we do in this class is pretty much the same sentence in the spring configuration file. In a nutshell, that's why I don't want to use the Spring framework with Druid, because this will only lead to the result that I don't know the other.

We then implement the DruidDao class in the dao package and begin to persist the data. Since we don't use persistence layer frameworks such as MyBatis, we have to use JDBC to manipulate the database, which is a bit of a hassle, but it's the basis of all frameworks.

1 / * * 2 * 3 * / 4 package dao; 5 6 import java.sql.PreparedStatement; 7 import java.sql.SQLException; 8 9 import com.alibaba.druid.pool.DruidPooledConnection;10 11 import util.DBPoolConnection;12 13 / * 14 * @ author ylf15 * 16 * 21 October 2016 17 * / 18 public class DruidDao {19 20 public void insert (String sql) {21 DBPoolConnection dbp = DBPoolConnection.getInstance () / / get data connection pool singleton 22 DruidPooledConnection conn = null;23 PreparedStatement ps = null;24 try {25 conn = dbp.getConnection (); / / get database connection 26 ps = conn.prepareStatement (sql) from database connection pool; 27 ps.executeUpdate (); 28} catch (SQLException e) {29 e.printStackTrace () 30} finally {31 try {32 if (null! = ps) {33 ps.close (); 34} 35 if (null! = conn) {36 conn.close () 37} 38} catch (Exception e) {39 e.printStackTrace (); 40} 41} 42} 43}

We only insert data. Let's test it. The meaning of each attribute can be found in: https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8

1 / * * 2 * 3 * / 4 package test; 5 6 import dao.DruidDao; 7 8 / * * 9 * @ author ylf10 * 11 * 21 October 2016 12 * / 13 public class Client {14 15 / * * 16 * @ param args17 * / 18 public static void main (String [] args) {19 DruidDao druidDao = new DruidDao (); 20 String sql = "insert into test (name) values (\" keven\ ") 21 druidDao.insert (sql); 22} 23 24}

Check that the database was inserted successfully.

In addition, the configuration file of the db_server.properties database is as follows:

DriverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/DruidTestusername=rootpassword=0000filters=statinitialSize=2maxActive=300maxWait=60000timeBetweenEvictionRunsMillis=60000minEvictableIdleTimeMillis=300000validationQuery=SELECT 1testWhileIdle=truetestOnBorrow=falsetestOnReturn=falsepoolPreparedStatements=falsemaxPoolPreparedStatementPerConnectionSize=200

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report