我有一个实时的 Java 服务器。它有一个用于数据库连接、操作和关闭的 DatabaseManager 类。但是有很多数据库活动正在进行(甚至超过 50 个客户端同时连接和投票)。executeQuery 方法返回一个 ResultSet,因此并不是每个打开的连接都会关闭,因为关闭会在返回之前清空 ResultSet。有没有更好的方法来解决这个问题?
public class DatabaseManager {
private Connection conn;
public static Logger logger;
public static String user = "root";
public static String pass = "";
public DatabaseManager() {
logger = LoggerFactory.getLogger("Utilities.DatabaseManager");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
}
}
public void startConnection() {
try {
conn = DriverManager.getConnection("jdbc:mysql:///youspinvotes",
user, pass);
logger.debug("Database connected");
} catch (SQLException e) {
logger.error("Unable to connect to Database");
logger.error(e.getMessage());
}
}
public ResultSet exececuteQuery(final String query) {
logger.debug("Executing query:" + query);
ResultSet resultSet = null;
try {
final Statement stmt = conn.createStatement();
resultSet = stmt.executeQuery(query);
logger.debug("Query executed");
} catch (Exception e) {
logger.error("Unable to execute query."+e.getLocalizedMessage());
resultSet = null;
}
return resultSet;
}
public int executeUpdate(final String query) {
logger.debug("Executing update query:" + query);
int rowsAffected = -1;
try {
final Statement stmt = conn.createStatement();
rowsAffected = stmt.executeUpdate(query);
stmt.close();
logger.debug("Update performed with "+rowsAffected+" rows changed.");
} catch (Exception e) {
logger.error(query + ": Unable to execute query. \n"+ e.getMessage());
}
return rowsAffected;
}
public void endConnection() {
logger.debug("Closing database connection");
try {
conn.close();
} catch (Exception e) {
logger.error("There was a problem closing the database connection.");
}
}
}
由于有很多创建和关闭连接,因此会消耗资源和时间。有什么办法可以提高性能吗?连接池是此服务器的好选择吗?实现这种服务器的最有效方法是什么?