gpt4 book ai didi

java - Hibernate 在多线程应用程序中随机抛出 "org.hibernate.exception.JDBCConnectionException: Could not open connection"

转载 作者:行者123 更新时间:2023-12-02 04:14:16 25 4
gpt4 key购买 nike

public class HibernateUtil {

private static SessionFactory INSTANCE_SESSION_FACTORY = null;

public enum Common {
SUCCESS, ROLLBACK
}

private synchronized static void createSessionFactory() {
try {
if (INSTANCE_SESSION_FACTORY != null) {
return;
}
ResourceBundle rb = ResourceBundle.getBundle("application");
Integer environment = Integer.valueOf(rb.getString("environment"));

Properties prop = new Properties();

switch (environment) {
/* LOCAL */
case 1:
prop.setProperty("hibernate.connection.driver_class", rb.getString("hibernate.driver.class.name"));
prop.setProperty("hibernate.connection.url", rb.getString("hibernate.db.uri"));
prop.setProperty("hibernate.connection.username", rb.getString("hibernate.db.username"));
prop.setProperty("hibernate.connection.password", rb.getString("hibernate.db.password"));
break;
default:
throw new ConfigurationException(environment == null ? "No environment added in application.properties"
: "Wrong environment added in application.properties");
}

prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
prop.setProperty("hibernate.show_sql", "true");
prop.setProperty("hibernate.hbm2ddl.auto", "update");
prop.setProperty("hibernate.current_session_context_class", "thread");
prop.setProperty("hibernate.connection.pool_size", "100");

prop.setProperty("hibernate.c3p0.minPoolSize", "5");
prop.setProperty("hibernate.c3p0.maxPoolSize", "100");
prop.setProperty("hibernate.c3p0.initialPoolSize", "10");
prop.setProperty("hibernate.c3p0.timeout", "1800");
prop.setProperty("hibernate.c3p0.max_statements=", "50");

org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration().addProperties(prop)
.addAnnotatedClass(Account.class).addAnnotatedClass(InsynctiveProperty.class)
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
.buildServiceRegistry();
INSTANCE_SESSION_FACTORY = config.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
if (INSTANCE_SESSION_FACTORY == null) {
createSessionFactory();
}
return INSTANCE_SESSION_FACTORY;
}

public static Session getCurrentSession() {
return getSessionFactory().getCurrentSession();
}

public static Session openSession() {
return getSessionFactory().openSession();
}

public static void closeCurrentSession() {
getSessionFactory().getCurrentSession().close();
}

public synchronized static Object get(Class<?> clazz, Integer id) {
Session session = getCurrentSession();
final Transaction transaction = session.beginTransaction();
try {
Object obj = session.get(clazz, id);
transaction.commit();
return obj;
} catch (RuntimeException ex) {
System.out.println(ex);
transaction.rollback();
throw ex;
} finally {

}
}

public Common save(Object object) {
Session session = openCurrentSession();
Transaction transaction = null;
Common result = null;
try {
transaction = openTransaction(session);
session.save(object);
transaction.commit();
result = Common.SUCCESS;
} catch (Exception e) {
e.printStackTrace();
if (transaction != null) {
transaction.rollback();
}
result = Common.ROLLBACK;
} finally {
session.close();
}

return result;
}

public Common update(Object object) {
Session session = openCurrentSession();
Transaction transaction = null;
Common result;

try {
transaction = openTransaction(session);
session.update(object);
transaction.commit();
result = Common.SUCCESS;
} catch (Exception e) {
e.printStackTrace();

if (transaction != null) {
transaction.rollback();
}
result = Common.ROLLBACK;
} finally {
session.close();
}
return result;
}

public Session openCurrentSession() {
return getSessionFactory().openSession();
}

public Transaction openTransaction(Session session) {
return session.beginTransaction();
}
}

有时,当使用这些方法之一时,我会收到此错误:

org.hibernate.exception.JDBCConnectionException: Could not open connection

[org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131), org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49), org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125), org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110), org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304), org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169), org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67), org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160), org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:483), org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352), com.sun.proxy.$Proxy66.beginTransaction(Unknown Source), insynctive.utils.HibernateUtil.get(HibernateUtil.java:123), insynctive.tests.TestMachine.tearUp(TestMachine.java:104), insynctive.tests.PersonFileTest.tearUp(PersonFileTest.java:52), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:483), org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85), org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:517), org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213), org.testng.internal.Invoker.invokeConfigurations(Invoker.java:140), org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:170), org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:104), org.testng.TestRunner.privateRun(TestRunner.java:771), org.testng.TestRunner.run(TestRunner.java:621), org.testng.SuiteRunner.runTest(SuiteRunner.java:357), org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352), org.testng.SuiteRunner.privateRun(SuiteRunner.java:310), org.testng.SuiteRunner.run(SuiteRunner.java:259), org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52), org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86), org.testng.TestNG.runSuitesSequentially(TestNG.java:1199), org.testng.TestNG.runSuitesLocally(TestNG.java:1124), org.testng.TestNG.run(TestNG.java:1032), insynctive.runnable.RunnableTest.run(RunnableTest.java:15), java.lang.Thread.run(Thread.java:745)]

SQLStateConversionDelegate.java:131

else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
return new JDBCConnectionException( message, sqlException, sql );

我需要重新启动池 session 才能继续工作..

知道发生了什么吗?我的应用程序是一个多线程应用程序,我抛出了6-10个线程

注意我使用 Heroku DB (ClearDB MySQL),当我使用本地数据库时,我无法重现此错误。

最佳答案

您已经实现了双重检查锁定模式。为了使其正常工作,您必须将 INSTANCE_SESSION_FACTORY 变量设为 volatile

请注意,这可能是也可能不是异常的原因,但它肯定是代码中的错误。

更新:

您可能只是遇到了池连接超时的情况。您可能想尝试启用 c3p0 的空闲连接检查(例如“idleConnectionTestPeriod=300”)。

关于java - Hibernate 在多线程应用程序中随机抛出 "org.hibernate.exception.JDBCConnectionException: Could not open connection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480327/

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