gpt4 book ai didi

java - 许多 MySQL 连接

转载 作者:可可西里 更新时间:2023-11-01 06:47:46 25 4
gpt4 key购买 nike

我对这个事实有点迷茫:

show status like 'con%';

+-----------------------------------+-------+
| Variable_name | Value |
+-----------------------------------+-------+
| Connection_errors_accept | 0 |
| Connection_errors_internal | 0 |
| Connection_errors_max_connections | 0 |
| Connection_errors_peer_address | 0 |
| Connection_errors_select | 0 |
| Connection_errors_tcpwrap | 0 |
| Connections | 10535 |
+-----------------------------------+-------+

我在这里读到一些类似的问题,但那些情况下的问题不是我的,所以我在这里。

我使用 MySQL 和 Hibernate。在我的 webapp 中有这个静态的 HibernateUtil 类来访问数据库:

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final Logger log = Logger.getLogger(HibernateUtil.class);
private static SessionFactory sessionFactory;

static {

try {
sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
// error handling
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {

Session s = null;
try {
s = (Session) session.get();
} catch(Exception e) {
// error handling
}

// Open a new Session, if this thread has none yet
if (s == null) {
try {
s = sessionFactory.openSession();
} catch(Exception e) {
// error handling
}

try {
s.getTransaction();
} catch(Exception e){
// error handling
}
Transaction tx = null;

while(tx==null){
try {
tx = s.beginTransaction();
// Store it in the ThreadLocal variable
} catch(Exception j) {
// error handling
}
}
session.set(s);
}
return s;
}


public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null){
try {
s.getTransaction().commit();
s.close();
} catch(Exception e) {
// error handling
}
}
session.set(null);
}

public static void errorSession() throws HibernateException {
Session s = (Session) session.get();
try {
s.getTransaction().rollback();
s.close();
} catch(Exception e) {
// error handling
}
session.set(null);
}

}

然后我像这个例子一样调用 util 类:

private MyTable getMyTable() {
try {
Session session = currentSession();
// some prepared statement
return myTable;
} catch (HibernateException e) {
errorSession();
return null;
} finally {
closeSession();
}
}

所以基本上我会在成功 (closeSession) 和错误 (errorSession) 时关闭连接。为什么我在 MySQL 控制台中看到这么多连接?

最佳答案

connections的意思不是你想的那样。如 docs 中所述connections 表示:

The number of connection attempts (successful or not) to the MySQL server.

所以你并没有像你想象的那样有 10535 个 Activity 连接。

关于java - 许多 MySQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100819/

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