java 如何创建新连接并稍后在 HikariCP 中检索它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26223116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:31:24  来源:igfitidea点击:

How to create new connections and retrieve them later in HikariCP

javahikaricp

提问by miniHessel

Would anyone care to elaborate how the HikariCP handles connections in the pool? How do you put a new connection in the pool, and how can you call on it / retrieve it later?

有人愿意详细说明 HikariCP 如何处理池中的连接吗?如何将新连接放入池中,稍后如何调用/检索它?

This is my current code:

这是我当前的代码:

    HikariConfig config = new HikariConfig();
    config.setMaximumPoolSize(100);

    config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.addDataSourceProperty("serverName", "localhost");
    config.addDataSourceProperty("port", "8889");
    config.addDataSourceProperty("databaseName", "XXX");
    config.addDataSourceProperty("user", "XXX");
    config.addDataSourceProperty("password", "XXX");

    System.out.print("qq");

    HikariDataSource ds = new HikariDataSource(config);
    ds.setConnectionTimeout(800);

回答by JB Nizet

With a pool, you don't add a connection to the pool to retrieve it later. You do the exact inverse: you get a connection from the pool when you need one, and close the connection when you're done with it to give it back to the pool. The HikariDataSource, as its name indicates, is a DataSource. A DataSource is an object from which you get connections.

使用池时,您无需向池中添加连接以便稍后检索它。你做的恰恰相反:当你需要一个连接时,你从池中获得一个连接,当你完成它时关闭连接,将它返回给池。HikariDataSource,顾名思义,是一个数据源。数据源是您从中获取连接的对象。

The pool handles the opening of the connection for you. It puts you in a waiting queue if no connections are available automatically, etc.

池为您处理连接的打开。如果没有自动可用的连接等,它会将您置于等待队列中。

Depending on the properties of the pool, the pool can open the connections immediately or on demand, keep a given number of connections always opened, shrink the pool size after given amount of unused time, etc.

根据池的属性,池可以立即或按需打开连接,保持给定数量的连接始终打开,在给定的未使用时间后缩小池大小等。

That's all very well documented: https://github.com/brettwooldridge/HikariCP#user-content-configuration-knobs-baby

这一切都有很好的记录:https: //github.com/brettwooldridge/HikariCP#user-content-configuration-knobs-baby

Example code (Java 7 and later):

示例代码(Java 7 及更高版本):

try (Connection connection = ds.getConnection()) {
    // use the connection
}

Example code (Before Java 7):

示例代码(Java 7 之前):

Connection connection = ds.getConnection();
try {
    // use the connection
}
finally {
    connection.close();
}