Application development based on LindormDataSource

更新时间:
复制 MD 格式

LindormDataSource is a high-performance JDBC connection pool for accessing Lindorm. It ships with optimized default settings and supports all Lindorm instance types—single-zone and multi-zone. For multi-zone wide table instances, it provides three access strategies: nearest-zone access, specified-zone access, and random-zone access.

Prerequisites

Before you begin, make sure you have:

Connection parameters

The parameters below apply to all examples in this topic.

LindormDataSource automatically injects optimized connection settings when it connects via the MySQL protocol, so you only need to provide the following parameters. See Auto-filled parameters for the full list of injected settings.

ParameterDescription
jdbcUrlJDBC connection URL. Format: jdbc:mysql://<MySQL-compatible endpoint>/<database name>. If no database name is specified, it defaults to default. To get the endpoint, see View endpoints.
usernameUsername for the wide table engine. To reset a forgotten password, see Change user password.
passwordPassword for the wide table engine.
Important
  • For applications deployed on an ECS instance, connect via a virtual private cloud (VPC) endpoint for better security and lower latency. Set jdbcUrl to the VPC endpoint.

  • For on-premises applications, enable the public endpoint first. Set jdbcUrl to the Internet endpoint.

Integrate JDBC applications

Step 1: Add dependencies

Add the following to the dependencies section of your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun.lindorm</groupId>
    <artifactId>lindorm-sql-datasource</artifactId>
    <version>2.2.1.4</version>
</dependency>

Step 2: Connect to Lindorm

Choose one of the following approaches:

  • Configuration file (recommended for production): Credentials are decoupled from code, making rotation and environment-specific overrides easier.

  • Business code: Convenient for quick local testing.

Option 1: Connect using a configuration file

  1. Create lindorm.properties in src/main/resources:

    jdbcUrl=jdbc:mysql://ld-bp1mq0tdzbx1m****-proxy-lindorm-pub.lindorm.aliyuncs.com:33060/default
    username=r***
    password=p***
    maximumPoolSize=30
  2. Load the configuration and create a DataSource in your business code:

    LindormDataSourceConfig config = new LindormDataSourceConfig("lindorm.properties");
    LindormDataSource lindormDataSource = new LindormDataSource(config);

Option 2: Connect in your business code

import com.aliyun.lindorm.sql.client.datasource.LindormDataSource;
import com.aliyun.lindorm.sql.client.datasource.LindormDataSourceConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LindormExample {
    public static void main(String[] args) throws Exception {
        // Configure the connection pool
        LindormDataSourceConfig config = new LindormDataSourceConfig();
        config.setJdbcUrl("jdbc:mysql://ld-bp1mq0tdzbx1m****-proxy-lindorm-pub.lindorm.aliyuncs.com:33060/database");
        config.setUsername("r***");
        config.setPassword("p***");
        config.setMaximumPoolSize(30);
        LindormDataSource lindormDataSource = new LindormDataSource(config);

        // Query a row by primary key
        try (Connection connection = lindormDataSource.getConnection()) {
            String sql = "SELECT * FROM " + tableName + " WHERE id=?";
            try (PreparedStatement ps = connection.prepareStatement(sql)) {
                ps.setString(1, "001");
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    System.out.println("id=" + rs.getString(1));
                    System.out.println("name=" + rs.getString(2));
                }
            }
        }
    }
}

Integrate Spring Boot 2.x applications

Step 1: Add dependencies

Add the following to the dependencies section of your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun.lindorm</groupId>
    <artifactId>lindorm-sql-datasource-springboot-starter</artifactId>
    <version>2.2.1.4</version>
</dependency>

Step 2: Add Spring configuration

Create application.yml in src/main/resources:

spring:
  datasource:
    lindorm:
      jdbc-url: jdbc:mysql://ld-bp167w8n1ab5p****-proxy-sql-lindorm.lindorm.rds.aliyuncs.com:33060/db1
      username: r***
      password: t***
      maximum-pool-size: 30

Step 3: Write your business code

@Service
public class DatabaseService {

  @Autowired
  private DataSource dataSource;

  public void createUser(User user) throws SQLException {
    String sql = "INSERT INTO users (name, age) VALUES (?, ?)";

    try (Connection conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql)) {
      ps.setString(1, user.getName());
      ps.setInt(2, user.getAge());
      ps.executeUpdate();
    }
  }
}

Integrate Spring Boot 3.x applications

Step 1: Add dependencies

Add the following to the dependencies section of your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun.lindorm</groupId>
    <artifactId>lindorm-sql-datasource-springboot-3-starter</artifactId>
    <version>2.2.1.4</version>
</dependency>

Step 2: Add Spring configuration

Create application.yml in src/main/resources:

spring:
  datasource:
    lindorm:
      jdbc-url: jdbc:mysql://ld-bp167w8n1ab5p****-proxy-sql-lindorm.lindorm.rds.aliyuncs.com:33060/db1
      username: r***
      password: r***
      maximum-pool-size: 30

Step 3: Write your business code

@Service
public class DatabaseService {

  @Autowired
  private DataSource dataSource;

  public void createUser(User user) throws SQLException {
    String sql = "INSERT INTO users (name, age) VALUES (?, ?)";

    try (Connection conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql)) {
      ps.setString(1, user.getName());
      ps.setInt(2, user.getAge());
      ps.executeUpdate();
    }
  }
}

Integrate MyBatis applications

When using MyBatis with Spring Boot, configure LindormDataSource within Spring Boot (see the Spring Boot sections above). The steps below apply to standalone MyBatis without Spring Boot.

Step 1: Add dependencies

Add the following to the dependencies section of your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun.lindorm</groupId>
    <artifactId>lindorm-sql-datasource</artifactId>
    <version>2.2.1.4</version>
</dependency>

Step 2: Connect to Lindorm

Choose one of the following approaches:

  • Configuration file (recommended for production): Externalizes credentials and connection settings.

  • Business code: Suitable for quick testing.

Option 1: Connect using a configuration file

  1. Define a DataSourceFactory compatible with MyBatis:

    package com.example.datasource;
    
    import com.aliyun.lindorm.sql.client.datasource.LindormDataSource;
    import com.aliyun.lindorm.sql.client.datasource.LindormDataSourceConfig;
    import org.apache.ibatis.datasource.DataSourceFactory;
    
    public class LindormDataSourceFactory implements DataSourceFactory {
      private Properties props;
    
      @Override
      public void setProperties(Properties props) {
        this.props = props;
      }
    
      @Override
      public DataSource getDataSource() {
        LindormDataSourceConfig config = new LindormDataSourceConfig(props);
        return new LindormDataSource(config);
      }
    }
  2. Create mybatis-config.xml in src/main/resources:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="com.example.datasource.LindormDataSourceFactory">
                    <property name="jdbcUrl"
                              value="jdbc:mysql://ld-8vbn68478unu8****-proxy-sql-lindorm.lindorm.rds.aliyuncs.com:33060/lindorm_test"/>
                    <property name="username" value="r***"/>
                    <property name="password" value="t***"/>
                    <property name="maximumPoolSize" value="30"/>
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <mapper class="com.example.mapper.UserMapper"/>
        </mappers>
    </configuration>
  3. Load the configuration and run your business logic:

    public static void main(String[] args) throws SQLException, IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
            new SqlSessionFactoryBuilder().build(inputStream);
    
        UserService userService = new UserService(sqlSessionFactory);
        userService.run();
    }

Option 2: Connect in your business code

SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

LindormDataSource dataSource = new LindormDataSource();
dataSource.setJdbcUrl("jdbc:mysql://ld-bp1mq0tdzbx1m****-proxy-lindorm-pub.lindorm.aliyuncs.com:33060");
dataSource.setUsername("r***");
dataSource.setPassword("r***");
sessionFactoryBean.setDataSource(dataSource);

SqlSessionFactory sessionFactory = sessionFactoryBean.getObject();
try (SqlSession session = sessionFactory.openSession(true)) {
    UserMapper mapper = session.getMapper(UserMapper.class);
    mapper.insert(user);
}

Optional configuration items

In most cases, the only parameter you need to tune is maximumPoolSize. All other parameters have production-ready defaults.

Configuration itemDescriptionDefault
maximumPoolSizeMaximum number of connections in the pool. Increase if you observe connection wait timeouts under high concurrency.10
minimumIdleMinimum number of idle connections kept alive. Defaults to maximumPoolSize, which keeps the pool fully warm. If the number of connections exceeds this value and a connection remains idle longer than the idleTimeout value, the connection closes.Equal to maximumPoolSize
connectionTimeoutMaximum time (ms) to wait when acquiring a connection from the pool.30000 (30 s)
keepaliveTimeInterval (ms) at which idle connections are validated to prevent silent disconnects.60000 (1 min)
idleTimeoutTime (ms) before an idle connection beyond minimumIdle is closed.600000 (10 min)
maxLifetimeMaximum lifetime (ms) of a connection before it is retired and replaced.1800000 (30 min)

Auto-filled parameters

When connecting via the MySQL protocol, LindormDataSource automatically injects the following parameters if they are not already present in the connection URL or Properties file. These defaults are tuned for Lindorm's SQL access patterns—avoid overriding them unless you have a specific reason to do so.

sslMode=DISABLED
allowPublicKeyRetrieval=true
useServerPrepStmts=true
useLocalSessionState=true
rewriteBatchedStatements=true
cachePrepStmts=true
prepStmtCacheSize=300
prepStmtCacheSqlLimit=50000000

For this reason, specify only the JDBC connection URL and target database in your connection string—for example, jdbc:mysql://ld-uf6k8yqb741t3****-proxy-sql-lindorm-public.lindorm.rds.aliyuncs.com:33060/default. Do not add extra connection configuration parameters to the URL.