gpt4 book ai didi

java - 不同客户端使用相同连接mysql JSP

转载 作者:行者123 更新时间:2023-11-29 12:25:10 25 4
gpt4 key购买 nike

我有一个 JPS 项目。

如果我有不同的计算机使用该系统,它们将使用相同的 MySQL 连接。

当系统运行任何查询并且客户端尝试执行任何 mysql 命令时,它会将每个人放入队列中,系统非常慢。

我希望每个客户端与 mysql 都有不同的连接。

抱歉,如果我不够清楚。

package br.com.scope.model;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;

import br.com.scope.log.LoggerIntegrador;

public class ConexaoMysql {
private static Connection connection;
private final static ConexaoMysql conexaoMysql = new ConexaoMysql();
private static Properties prop;
private LoggerIntegrador logger;

private ConexaoMysql() {
super();
prop = new Properties();
Class<? extends ConexaoMysql> cls = this.getClass();
InputStream is = cls.getResourceAsStream("db.properties");
try {
prop.load(is);
} catch (IOException e) {
logger = LoggerIntegrador.getInstance();
logger.error(e.getMessage(), e);
}
}

public static ConexaoMysql getConnection() throws SQLException, ClassNotFoundException, IOException {
if (connection == null || connection.isClosed()){
conexaoMysql.abreConexao();
}
return conexaoMysql;
}

public static void beginTransaction() throws SQLException, ClassNotFoundException, IOException {
getConnection();
connection.setAutoCommit(false);
}

public static void commit() throws SQLException {
connection.commit();
connection.setAutoCommit(true);
}

public static String getDriver() {
return prop.getProperty("driver");
}

public static String getConnectionString() {
return prop.getProperty("connectionstring");
}

public static String getUser() {
return prop.getProperty("user");
}

public static String getPassword() {
return prop.getProperty("password");
}

private void abreConexao() throws ClassNotFoundException, SQLException, IOException{
Class.forName(getDriver());

connection = DriverManager.getConnection(
getConnectionString(),
getUser(),
getPassword());
}

public static void fechaConexao() throws SQLException {
if (!connection.isClosed()) {
connection.close();
}
}

public PreparedStatement getPreparedStatement(String sql) throws SQLException {
return connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}

public static int getId() {
return conexaoMysql.hashCode();
}
}

最佳答案

您正在寻找的是连接池。它是一个有界连接池,客户端可以在需要时从中获取连接,并在完成时将其放回。这可以节省您的开销或始终创建和销毁连接。它还确保连接数量可预测地增长。

大多数容器都提供这样的设施,例如这是documentation for configuring a connection pool in Tomcat 。找到适合您的容器的那个。

如果由于某种原因您无法使用它或不希望容器负责,您可以使用一个库来帮助您在应用程序中自行管理连接池。 c3p0是一个受到很多人欢迎的examples在网络上。

编辑: Hikari是连接池的新酷选择。

关于java - 不同客户端使用相同连接mysql JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28439295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com