我有一个应用程序,其中包含多个按密钥分片的 Azure SQL 数据库。每次打开分片数据库连接时,我们都会检索 ShardMapManager 和 ListShardMap:
public static ShardMapManager CreateOrGetShardMapManager(string shardMapManagerConnectionString)
{
// Get shard map manager database connection string
// Try to get a reference to the Shard Map Manager in the Shard Map Manager database. If it doesn't already exist, then create it.
ShardMapManager shardMapManager = default(ShardMapManager);
bool shardMapManagerExists = ShardMapManagerFactory.TryGetSqlShardMapManager(shardMapManagerConnectionString, ShardMapManagerLoadPolicy.Lazy, out shardMapManager);
if (!shardMapManagerExists)
{
// The Shard Map Manager does not exist, so create it
shardMapManager = ShardMapManagerFactory.CreateSqlShardMapManager(shardMapManagerConnectionString);
}
return shardMapManager;
}
public static ListShardMap<T> CreateOrGetListMap<T>(ShardMapManager shardMapManager, string shardMapName)
{
// Try to get a reference to the Shard Map.
ListShardMap<T> shardMap = null;
bool shardMapExists = shardMapManager.TryGetListShardMap(shardMapName, out shardMap);
if (!shardMapExists)
{
// The Shard Map does not exist, so create it
shardMap = shardMapManager.CreateListShardMap<T>(shardMapName);
}
return shardMap;
}
然后我们通过将分片键传递给来打开一个连接OpenConnectionForKey()
:
public static DbConnection CreateShardConnection(int shardingKey, string connectionStr, string shardMapName)
{
var shardMapManager = CreateOrGetShardMapManager(connectionStr);
var shardMap = CreateOrGetListMap<int>(shardMapManager, shardMapName);
SqlConnection conn = shardMap.OpenConnectionForKey<int>(shardingKey, GenerateCredentialsConnString(connectionStr), ConnectionOptions.Validate);
return conn;
}
我们只对所有分片使用一个分片映射和一个列表映射,所以我的问题是——我们可以将这些对象缓存在一个全局变量中吗?它们是否设计为线程安全的,是否有助于提高性能?
更新
我在这里发现https://docs.microsoft.com/en-us/azure/sql-database/sql-database-elastic-scale-shard-map-management#constructing-a-shardmapmanager确实ShardMapManager
应该创建一次并且存储在全局变量中。
但是ListShardMap
呢?如果我们只有一个,我们也可以将它存储在一个全局变量中吗?