背景
业务侧分库分表
根据账户切换不同数据库,多个账户在同一个库。例如0001-0005的客户在一个库。
根据账户分表,账户名_表名
其实使用mongodb不用业务侧做这种分库分表,历史原因,还是实现了。
分库
springboot mongodb 的 MongoTemplate 默认是一个database。我们需要动态切换。所以需要改造。
通过跟踪MongoTemplate构造我们发现,有一个关键的类MongoDatabaseFactory
database工厂。
这个接口定义了一个方法getMongoDatabase()
。而且他有一个简单的实现SimpleMongoClientDatabaseFactory
。其中getMongoDatabase()
获取的就是我们配置文件中的数据库名.
// 默认的实现,getDefaultDatabaseName() 就是配置文件中的 database
public MongoDatabase getMongoDatabase() throws DataAccessException {
return getMongoDatabase(getDefaultDatabaseName());
}
按照SimpleMongoClientDatabaseFactory
自己实现一个Factory, 其他不变,重写getMongoDatabase()
/**
* 动态的 DynamicMongoDbFactory
*
* @author fengyi
* @version 1.0
* @date 2021/3/13 18:41
*/
public class DynamicMongoDbFactory extends MongoDatabaseFactorySupport<MongoClient>
implements DisposableBean {
private final static Logger LOG = LoggerFactory.getLogger(DynamicMongoDbFactory.class);
/**
* Creates a new {@link DynamicMongoDbFactory} instance for the given {@code connectionString}.
*
* @param connectionString connection coordinates for a database connection. Must contain a database name and must not
* be {@literal null} or empty.
* @see <a href="https://docs.mongodb.com/manual/reference/connection-string/">MongoDB Connection String reference</a>
*/
public DynamicMongoDbFactory(String connectionString) {
this(new ConnectionString(connectionString));
}
/**
* Creates a new {@link DynamicMongoDbFactory} instance from the given {@link MongoClient}.
*
* @param connectionString connection coordinates for a database connection. Must contain also a database name and not
* be {@literal null}.
*/
public DynamicMongoDbFactory(ConnectionString connectionString) {
this(MongoClients.create(connectionString), connectionString.getDatabase(), true);
}
/**
* Creates a new {@link DynamicMongoDbFactory} instance from the given {@link MongoClient}.
*
* @param mongoClient must not be {@literal null}.
* @param databaseName must not be {@literal null} or empty.
*/
public DynamicMongoDbFactory(MongoClient mongoClient, String databaseName) {
this(mongoClient, databaseName, false);
}
/**
* Creates a new {@link DynamicMongoDbFactory} instance from the given {@link MongoClient}.
*
* @param mongoClient must not be {@literal null}.
* @param databaseName must not be {@literal null} or empty.
* @param mongoInstanceCreated
*/
DynamicMongoDbFactory(MongoClient mongoClient, String databaseName, boolean mongoInstanceCreated)<