我有一个应用程序,该应用程序具有由密钥碎片的多个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;
}
我们只为所有碎片使用一个碎片地图和一个列表映射,所以我的问题是 - 我们可以在全局变量中缓存这些对象吗?它们的设计是安全的,它将有助于性能吗?
update
我在这里找到https://learn.microsoft.com/en-us/azure/sql-database/sql-database-lastic-scale-scale-scale-scale-scale-scale-scale-scale-scale-management#constructing-constructing-a-a-shardmapmanager确实应该ShardMapManager
可以创建一次并存储在全局变量中。
但是ListShardMap
呢?如果我们只有一个,我们也可以将其存储在全局变量中吗?
shardmapmanager包含映射的缓存,如果我们有多个缓存,那么(a)我们将由于重复项而消耗更多的内存,并且(b)我们总体上会获得更多的缓存误差,这两者都会导致性能较差。因此,我们想拥有一个Singleton Shardmapmanager,以便只有一个缓存的副本。
ListShardMap包含对创建它的Shardmapmanager的内部引用,以便它可以引用此缓存。如果您从同一shardmapmanager创建多个listShardMap实例,则它们都参考同一缓存(该SMM内部),因此完全可以。