2

我有一个应用程序,其中包含多个按密钥分片的 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呢?如果我们只有一个,我们也可以将它存储在一个全局变量中吗?

4

1 回答 1

1

ShardMapManager 包含一个映射缓存,如果我们有多个缓存,那么 (a) 我们会因为重复而消耗更多的内存,并且 (b) 我们总体上会得到更多的缓存未命中,这两者都会导致性能下降。所以我们想要一个单例 ShardMapManager 以便只有一个缓存副本。

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

于 2019-02-22T19:39:56.360 回答