← Back to alibaba/druid

How to Deploy & Use alibaba/druid

Druid Deployment & Usage Guide

A comprehensive guide for deploying and using Alibaba Druid, a high-performance database connection pool with built-in monitoring and SQL parsing capabilities.

1. Prerequisites

  • Java Development Kit: JDK 8 or higher (JDK 11/17 recommended for production)
  • Apache Maven: Version 3.6.0 or higher
  • Git: For cloning the repository
  • Database: MySQL, PostgreSQL, Oracle, SQLServer, or any JDBC-compliant database (for integration testing)
  • Optional: Docker (for containerized deployment)

2. Installation

2.1 Clone and Build from Source

# Clone the repository
git clone https://github.com/alibaba/druid.git
cd druid

# Build and install to local Maven repository
mvn clean install -DskipTests

# Run with tests (requires database configuration)
mvn clean install

2.2 Maven Dependency (Recommended)

Add Druid to your project via Maven Central:

Core Library:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.20</version>
</dependency>

Spring Boot Starter:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.20</version>
</dependency>

3. Configuration

3.1 Basic JDBC Configuration

Create druid.properties in src/main/resources:

# Database connection
url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
username=root
password=your_password
driverClassName=com.mysql.cj.jdbc.Driver

# Connection pool sizing
initialSize=5
maxActive=20
minIdle=5
maxWait=60000

# Validation queries
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false

# Time configuration
minEvictableIdleTimeMillis=300000
timeBetweenEvictionRunsMillis=60000

3.2 Spring Boot Configuration (application.yml)

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/mydb?useSSL=false
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
    
    druid:
      # Pool configuration
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      
      # Filters for monitoring and security
      filters: stat,wall,log4j2
      
      # Stat filter configuration
      filter:
        stat:
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: true
        wall:
          enabled: true
          config:
            select-allow: true
            update-allow: true
            insert-allow: true
            delete-allow: false  # Disable deletes via WallFilter
      
      # Web monitoring console
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: admin
        reset-enable: false

3.3 Multi-Dialect SQL Parser Configuration

For SQL parsing and schema repository features:

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.repository.SchemaRepository;

// Configure parser for specific database dialect
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(
    "SELECT * FROM users WHERE id = 1", 
    DbType.mysql
);

// Schema repository for metadata management
SchemaRepository repository = new SchemaRepository(DbType.mysql);
repository.acceptDDL("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50))");

4. Build & Run

4.1 Local Development Build

# Clean build without tests
mvn clean install -DskipTests -Dmaven.javadoc.skip=true

# Build specific module (e.g., core)
mvn clean install -pl core

# Build with specific JDK version
mvn clean install -Djava.version=11

4.2 Running Tests

# Run all tests (requires test database configuration)
mvn test

# Run specific test class
mvn test -Dtest=FnvHashTest

# Run with PostgreSQL dialect tests
mvn test -Dtest=PGSQLStatementParserTest

4.3 Basic Usage Example

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

public class DruidExample {
    
    public static DataSource createDataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        
        // Basic configuration
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        // Pool configuration
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(5);
        dataSource.setMaxWait(60000);
        
        // Enable monitoring filters
        dataSource.setFilters("stat,wall");
        
        // Initialize pool
        dataSource.init();
        
        return dataSource;
    }
    
    public static void queryData(DataSource dataSource) throws SQLException {
        try (DruidPooledConnection conn = (DruidPooledConnection) dataSource.getConnection()) {
            // Execute queries
            // Connection automatically returned to pool on close
        }
    }
}

4.4 Spring Boot Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DruidApplication {
    public static void main(String[] args) {
        SpringApplication.run(DruidApplication.class, args);
    }
}

// Service usage
import org.springframework.beans.factory.annotation.Autowired;
import javax.sql.DataSource;

@Service
public class UserService {
    @Autowired
    private DataSource dataSource;  // Injected DruidDataSource
    
    public void processData() {
        // Use dataSource for database operations
    }
}

5. Deployment

5.1 Library Integration (Most Common)

Druid is primarily used as a library dependency. Deploy your application with Druid embedded:

<!-- pom.xml production profile -->
<profile>
    <id>production</id>
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</profile>

5.2 Docker Deployment

Dockerfile for Spring Boot app with Druid:

FROM openjdk:17-jdk-slim
VOLUME /tmp
COPY target/myapp.jar app.jar

# JVM optimizations for Druid connection pool
ENV JAVA_OPTS="-XX:+UseG1GC -XX:MaxRAMPercentage=75.0 -Djava.security.egd=file:/dev/./urandom"

ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar /app.jar"]

docker-compose.yml:

version: '3.8'
services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://db:3306/mydb
      - SPRING_DATASOURCE_DRUID_USERNAME=app_user
      - SPRING_DATASOURCE_DRUID_PASSWORD=secure_password
      - SPRING_DATASOURCE_DRUID_MAX_ACTIVE=50
    depends_on:
      - db
  
  db:
    image: mysql:8.0
    environment:
      - MYSQL_ROOT_PASSWORD=root_password
      - MYSQL_DATABASE=mydb
    ports:
      - "3306:3306"

5.3 Production Configuration

High-Concurrency Settings:

# Production-optimized pool settings
maxActive=100
initialSize=20
minIdle=20
maxWait=30000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
maxEvictableIdleTimeMillis=600000
keepAlive=true
keepAliveBetweenTimeMillis=60000

# Connection validation
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=20

# Monitoring (disable reset in production)
druid.stat.mergeSql=true
druid.stat.slowSqlMillis=3000

6. Troubleshooting

6.1 Connection Leaks

Symptom: java.sql.SQLException: connection holder is null or pool exhaustion.

Solution:

// Enable connection leak detection
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(300); // 5 minutes
dataSource.setLogAbandoned(true); // Log stack trace of abandoned connections

6.2 Memory Issues

Symptom: OutOfMemoryError or high GC pressure.

Solutions:

  • Reduce maxActive if too high for available memory
  • Enable keepAlive to prevent connection expiration pile-up
  • Set maxEvictableIdleTimeMillis to prevent indefinite connection holding
  • Monitor via /druid/datasource.html console

6.3 SQL Injection Protection

Symptom: WallFilter blocking legitimate queries or allowing malicious ones.

Configuration:

WallConfig config = new WallConfig();
config.setSelectAllow(true);
config.setUpdateAllow(true);
config.setDeleteAllow(true);
config.setInsertAllow(true);
config.setMultiStatementAllow(false); // Prevent stacked queries
config.setNoneBaseStatementAllow(false); // Prevent DDL if not needed

WallFilter filter = new WallFilter();
filter.setConfig(config);
filter.setDbType(DbType.mysql);
dataSource.getProxyFilters().add(filter);

6.4 Parser Compatibility Issues

Symptom: ParserException for valid SQL on specific databases.

Solution:

// Explicitly specify database dialect
import com.alibaba.druid.DbType;

// For PostgreSQL specific syntax
PGSQLStatementParser parser = new PGSQLStatementParser(sql);
SQLStatement statement = parser.parseStatement();

// Or use utility with correct DbType
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(
    sql, 
    DbType.postgresql
);

6.5 Spring Boot Auto-Configuration Conflicts

Symptom: DataSource bean not of type DruidDataSource.

Solution:

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.druid")
    public DataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }
    
    // Exclude default DataSource auto-config if needed
    @SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class
    })
    public static class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
}

6.6 Monitoring Console Access

Access URL: http://localhost:8080/druid/index.html

Common Issues:

  • 404 Error: Ensure StatViewServlet is enabled in configuration
  • Login Failed: Verify login-username and login-password match configuration
  • No Data: Check that filters includes stat and application has executed SQL queries

Security Note: In production, restrict access to /druid/* endpoints using Spring Security or reverse proxy (Nginx/Apache) IP restrictions.