我的要求如下:
我需要使用从外部获取的新 HBM 文件频繁地在我的 Spring Web 应用程序中重新启动(或重建)休眠会话工厂。
目前我的 Sessionfactory 类如下,带有一个 SessionFactory 代理来拦截“OpenSession”调用。
在那里,我正在检查重新启动和重建 sessionFactory 的条件。
我的问题是,在并发环境中,处于其他事务中间的其他用户在重新启动期间受到影响。
无论如何通过检查所有事务和打开会话并在所有其他完成后执行重建会话工厂来执行重新启动?
或存在任何其他解决方案。
代码:
public class DataStoreSessionFactory extends LocalSessionFactoryBean
{
private boolean restartFactory = false;
@Override
protected void postProcessConfiguration(Configuration config) throws HibernateException
{
super.postProcessConfiguration(config);
updateHBMList(config);
}
private void updateHBMList(final Configuration config)
{
config.addXML(modelRegistry.generateMapping());
}
@Override
public SessionFactory getObject()
{
Object obj = super.getObject();
/*
* Invocation handler for the proxy
*/
SessionFactoryProxy proxy = new SessionFactoryProxy(this, (SessionFactory) obj);
/**
* All the methods invoked on the returned session factory object will pass through this proxy's invocation
* handler
*/
SessionFactory sessionFactory = (SessionFactory) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { SessionFactory.class },
proxy);
return sessionFactory;
}
static class SessionFactoryProxy implements InvocationHandler
{
private SessionFactory sessionFactory;
private LocalSessionFactoryBean factoryBean;
public SessionFactoryProxy(LocalSessionFactoryBean factoryBean, SessionFactory sessionFactory)
{
this.factoryBean = factoryBean;
this.sessionFactory = sessionFactory;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
/**
* Only if the method invoked is openSession - check if the session factory should be restarted, and only then
* invoke the requested method
*/
if (method.getName().equals("openSession"))
{
restartSessionFactoryIfNecessary();
}
return method.invoke(sessionFactory, args);
}
private void restartSessionFactoryIfNecessary()
{
restartSessionFactory();
/*if (((DataStoreSessionFactory) factoryBean).isRestartFactory())
{
restartSessionFactory();
}*/
}
private synchronized void restartSessionFactory()
{
log.info("Restarting session...");
factoryBean.destroy();
try
{
factoryBean.afterPropertiesSet();
sessionFactory = factoryBean.getObject();
}
catch (Exception e)
{
log.error("Error while restarting session: " + e.getMessage());
throw new RuntimeException(e);
}
}
}
谢谢,阿帕萨米