Spring-JPA EntityManager如何处理“损坏"的消息?连接? [英] How does Spring-JPA EntityManager handle "broken" connections?

查看:226
本文介绍了Spring-JPA EntityManager如何处理“损坏"的消息?连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Spring-EntityManager(JPA)的应用程序,我想知道如果在上述应用程序的生存期内该数据库不可用,会发生什么情况.

I have an application that uses a Spring-EntityManager (JPA) and I wonder what happens if the database happens to be unavailable during the lifetime of my aforesaid application.

我希望在这种情况下,它将在第一次对数据库执行任何操作时引发异常,对吗?

I expect in that situation it will throw an exception the first time to do anything on the database, right?

但是,说我等了10分钟,然后重试,数据库碰巧又回来了.它会恢复吗?我可以安排它吗?

But, say I wait 10 minutes and try again then and the DB happens to be back. Will it recover? Can I arrange it so it does?

谢谢

推荐答案

实际上,Spring和JPA都与此无关.内部所有持久性框架只需调用 DataSource.getConnection() 并期望接收(可能是池化的)JDBC连接.完成后,它们close()连接有效地将其返回到池中.

Actually, neither Spring nor JPA have anything to do with it. Internally all persistence frameworks simply call DataSource.getConnection() and expect to receive (probably pooled) JDBC connection. Once they're done, they close() the connection effectively returning it to the pool.

现在,当要求DataSource建立连接但数据库无法恢复连接时,它将引发异常.该异常将会传播,并且将由您使用的任何框架以某种方式处理.

Now when the DataSource is asked to give a connection but database is unaivalable it will throw an exception. That exception will propagate up and will be somehow handled by whatever framework you use.

现在回答您的问题-通常是DataSource实现(例如等. )将丢弃已知已断开的连接,并换上新的连接.它确实取决于提供程序,但是您可以放心地假设,一旦数据库再次可用,DataSource将逐渐摆脱 sick 连接,并用 healthy 替换它们.一个.

Now to answer your question - typically DataSource implementation (like dbcp, c3p0, etc.) will discard connection known to be broken and replace it with a fresh one. It really depends on the provider, but you can safely assume that once the database is available again, the DataSource will gradually get rid of sick connections and replace them with healthy ones.

还有许多DataSource实现者提供了定期测试连接并在将其返回给客户端之前进行测试的方法.这在DataSource包含连接池的池环境中很重要,而当数据库不可用时,它将无法发现该池.因此,某些DataSource的测试连接(通过调用SELECT 1或类似方法)在将其返回给客户端之前不时进行一次以消除断开的连接,例如由于基础TCP连接中断.

Also many DataSource implementors provide ways of testing the connection periodically and before it is returned to the client. This is important in pooled environemnts where the DataSource contains a pool of connections and when the database becomes unavailable it has no way to discover that. So some DataSources test connection (by calling SELECT 1 or similar) before giving it back to the client and do the same once in a while to get rid of broken connections, e.g. due to broken underlying TCP connection.

,您将得到一个异常,并且,一旦数据库恢复,系统将正常运行.顺便说一句,您可以轻松测试一下!

Yes, you will get an exception and yes the system will work normally once the database is back. BTW you can easily test this!

这篇关于Spring-JPA EntityManager如何处理“损坏"的消息?连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆