ShardMapManager和ShardMap对象是否应该作为一个整体全局缓存?

时间:2019-02-22 16:08:00

标签: c# entity-framework azure-sql-database azure-elastic-scale azure-elastic-sharding

我有一个具有多个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呢?如果只有一个,是否也可以将其存储在全局变量中?

1 个答案:

答案 0 :(得分:0)

ShardMapManager包含一个映射缓存,如果我们有多个缓存,则(a)由于重复我们将消耗更多的内存,并且(b)我们总体上将获得更多的缓存未命中,这两者都会导致性能下降。因此,我们想要一个单例ShardMapManager以便仅拥有一个缓存副本。

ListShardMap包含对创建它的ShardMapManager的内部引用,以便它可以引用此缓存。如果您从同一个ShardMapManager创建多个ListShardMap实例,它们都引用同一个缓存(在该SMM内),因此完全没问题。