更新时间:2023-09-18 23:06:34
首先,每个用户数据库是一个非常不常见的设计.如果所有这些数据库都以相同的结构结尾,请不要在实际应用程序中这样做,而只需在表和查询中添加user_id.
First, per user database is a very uncommon design. If all those databases will end with same structure, please do not do that in a real world application, but just add user_id in your tables and queries.
接下来,我在我的另一个答案中找到了另一个动态AbstractRoutingDataSource的示例(未完整).
Next, I found another (not full) example of a dynamic AbstractRoutingDataSource in another answer of mine.
我的代码(请注意,未经测试)与您的问题之间的一大区别是,我使用SessionListener关闭数据库,以避免打开的数据库的数量不确定地增加.
And one big difference between my code (beware never tested) and your question is that I use a SessionListener to close the databases to avoid that the number of open database grows indefinitively.
如果您要学习Spring,可以尝试以下模式(自下而上的描述):
If you to this to learn Spring, you could try the following pattern (bottom-up description) :
AbstractRoutingDataSource
,将被注入到上述持有人的代理服务器,并将向持有人询问实际数据来源AbstractRoutingDataSource
, that would be injected with a proxy to above holder, and that would ask actual datasource to the holder与其他答案一样,如果同一用户可能同时进行多个会话,则可以在会话持有者中注入一个单例,以保持实际的数据库连接以及活动会话的数量.这样,无论他有多少个并发会话,每个用户都将获得一个单一连接.
As in the other answer, if same user is likely to have many simultaneous sessions, you could have a singleton been injected in session holders that would keep the actual database connections along with the number of active sessions. That way you would get one single connection per user, no matter how many concurrent sessions he could have.