Skip to content

Commit a49e9b3

Browse files
committed
improved scale-out algorithm
1 parent fc74bbb commit a49e9b3

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

app/Services/ScaleOut.cs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public class ScaleOut : IScaleOut
2626
private readonly ILogger<ScaleOut> _logger;
2727
private DateTime _lastCall = DateTime.Now;
2828
private string _lastConnectionString = string.Empty;
29+
private List<String> _replicaConnectionString = new List<String>();
2930

3031
public ScaleOut(IConfiguration config, ILogger<ScaleOut> logger)
3132
{
@@ -44,6 +45,7 @@ public string GetConnectionString(ConnectionIntent connectionIntent)
4445

4546
var rnd = new Random();
4647

48+
// Get the list of available named replica from the primary replica
4749
// Add some randomness to avoid the "thundering herd" problem
4850
if (elapsed.TotalMilliseconds > rnd.Next(3500, 5500))
4951
{
@@ -57,25 +59,26 @@ public string GetConnectionString(ConnectionIntent connectionIntent)
5759
commandType: CommandType.StoredProcedure
5860
).AsList();
5961

60-
if (databases.Count > 0)
62+
_replicaConnectionString = new List<string>();
63+
foreach(var d in databases)
6164
{
62-
var i = rnd.Next(databases.Count);
63-
database = databases[i];
64-
_logger.LogDebug(database);
65+
var csb = new SqlConnectionStringBuilder(connString);
66+
if (!string.IsNullOrEmpty(d))
67+
csb.InitialCatalog = d;
68+
69+
_replicaConnectionString.Add(csb.ToString());
6570
}
66-
}
67-
68-
var csb = new SqlConnectionStringBuilder(connString);
69-
if (!string.IsNullOrEmpty(database))
70-
csb.InitialCatalog = database;
71-
72-
result = csb.ConnectionString;
7371

74-
_lastCall = DateTime.Now;
75-
_lastConnectionString = result;
76-
} else {
77-
result = _lastConnectionString;
72+
_lastCall = DateTime.Now;
73+
}
7874
}
75+
76+
// Get a connection string randomly
77+
if (_replicaConnectionString.Count > 0)
78+
{
79+
var i = rnd.Next(_replicaConnectionString.Count);
80+
result = _replicaConnectionString[i];
81+
}
7982

8083
return result;
8184
}

0 commit comments

Comments
 (0)