我使用 Spring MVC + Hibernate 开发了一个 Web 应用程序,在运行负载测试时,似乎垃圾收集器被调用得太频繁。我担心这可能与我管理 Hibernates session 的方式有关。
我有一个 AbstractDao,我的所有 DAO 对象都扩展了它:
public class AbstractDaoHibernateImpl {
protected GenericDataBaseExceptionHandler exceptionHandler;
private SessionFactory sessionFactory;
public AbstractDaoHibernateImpl() {
}
public void setExceptionHandler(GenericDataBaseExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
}
在 Spring 实体 bean 配置中,我定义了每个 DAO,如下所示:
<bean name="userDao" class="com.kelmer.dao.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
<property name="exceptionHandler" ref="defaultSpringExceptionHandler" />
</bean>
这是我的一个 DAO 中的示例方法:
@Override
public EstacionVO findById(Long id) throws InstanceNotFoundException {
User e = (User ) getSession().createQuery(SELECT_USER_BY_ID).setParameter("userId", id).uniqueResult();
if (e == null) {
throw new InstanceNotFoundException ("No user with provided Id", User.class);
}
return e;
}
老实说,我可以看到任何可能导致内存泄漏的内容,但话又说回来,我并不是真正的专家。我的 session 管理正确吗?我知道我从一些遗留代码中获取了 AbstractDao 的代码,我担心这可能是内存问题的所在,因为没有显式的 session 关闭或终结。
PS。对于事务管理,我使用<tx:annotation-driven />
在 spring 上下文中并用 @Transactional
注释每个方法.
最佳答案
乍一看,您的代码似乎没有任何异常。
运行性能监视器以查看创建了哪些对象。
除非问题很微不足道,否则仅通过查看代码很难看出性能损失在哪里,并且 90% 的情况下,任何“一定是这个”的陈述都会被证明是错误的。
关于java - 使用 Hibernate 的高 GC 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435250/