配置
因為有很多不同的方式來配置 redis,所以 StackExchange.Redis 提供了一個豐富的配置模型,該模型在調用 Connect
(或ConnectAsync
)時被調用:
var conn = ConnectionMultiplexer.Connect(configuration);
這里的配置可以是:
ConfigurationOptions
實例- 配置字符串
后者基本上是前者的標記形式。
基礎配置字符串
最簡單的配置示例就是主機名:
var conn = ConnectionMultiplexer.Connect("localhost");
這使用默認的redis端口(6379)連接到本地計算機上的單個服務器。其他選項只是簡單地附加(以逗號分隔)。通常,端口用冒號(:)表示,配置選項在名稱后包括=,例如:
var conn = ConnectionMultiplexer.Connect("redis0:6380,redis1:6380,allowAdmin=true");
如果在連接字符串中指定了 serviceName
,它將觸發前哨模式。
以下示例表示使用默認的哨兵端口(26379)連接到本地計算機上的哨兵服務器,發現 mymaster
服務的當前主服務器,並返回指向 master 服務器的托管連接。如果 master 服務器發生更改,托管連接將自動更新:
var conn = ConnectionMultiplexer.Connect("localhost,serviceName=mymaster");
字符串和 ConfigurationOptions
切換非常簡單:
ConfigurationOptions options = ConfigurationOptions.Parse(configString);
或者:
string configString = options.ToString();
A common usage is to store the basic details in a string, and then apply specific details at runtime:
一種常見用法是將基本信息保存在字符串中,然后在運行時賦值:
string configString = GetRedisConfiguration();
var options = ConfigurationOptions.Parse(configString);
options.ClientName = GetAppName(); // only known at runtime
options.AllowAdmin = true;
conn = ConnectionMultiplexer.Connect(options);
Microsoft Azure Redis 示例:
var conn = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");
配置選項
ConfigurationOptions
對象有很多屬性,一些較常用的選項包括:
Configuration string | ConfigurationOptions | Default | Meaning |
---|---|---|---|
abortConnect={bool} | AbortOnConnectFail | true (false on Azure) | If true, Connect will not create a connection while no servers are available |
allowAdmin={bool} | AllowAdmin | false | Enables a range of commands that are considered risky |
channelPrefix={string} | ChannelPrefix | null | Optional channel prefix for all pub/sub operations |
connectRetry={int} | ConnectRetry | 3 | The number of times to repeat connect attempts during initial Connect |
connectTimeout={int} | ConnectTimeout | 5000 | Timeout (ms) for connect operations |
configChannel={string} | ConfigurationChannel | __Booksleeve_MasterChanged | Broadcast channel name for communicating configuration changes |
configCheckSeconds={int} | ConfigCheckSeconds | 60 | Time (seconds) to check configuration. This serves as a keep-alive for interactive sockets, if it is supported. |
defaultDatabase={int} | DefaultDatabase | null | Default database index, from 0 to databases - 1 |
keepAlive={int} | KeepAlive | -1 | Time (seconds) at which to send a message to help keep sockets alive (60 sec default) |
name={string} | ClientName | null | Identification for the connection within redis |
password={string} | Password | null | Password for the redis server |
user={string} | User | null | User for the redis server (for use with ACLs on redis 6 and above) |
proxy={proxy type} | Proxy | Proxy.None | Type of proxy in use (if any); for example "twemproxy" |
resolveDns={bool} | ResolveDns | false | Specifies that DNS resolution should be explicit and eager, rather than implicit |
serviceName={string} | ServiceName | null | Used for connecting to a sentinel master service |
ssl={bool} | Ssl | false | Specifies that SSL encryption should be used |
sslHost={string} | SslHost | null | Enforces a particular SSL host identity on the server's certificate |
sslProtocols={enum} | SslProtocols | null | Ssl/Tls versions supported when using an encrypted connection. Use ' |
syncTimeout={int} | SyncTimeout | 5000 | Time (ms) to allow for synchronous operations |
asyncTimeout={int} | AsyncTimeout | SyncTimeout |
Time (ms) to allow for asynchronous operations |
tiebreaker={string} | TieBreaker | __Booksleeve_TieBreak | Key to use for selecting a server in an ambiguous master scenario |
version={string} | DefaultVersion | (3.0 in Azure, else 2.0) | Redis version level (useful when the server does not make this available) |
CheckCertificateRevocation | true | A Boolean value that specifies whether the certificate revocation list is checked during authentication. |
其他硬編碼選項:
- ReconnectRetryPolicy (IReconnectRetryPolicy) - Default: ReconnectRetryPolicy = LinearRetry(ConnectTimeout);
配置字符串中的令牌以逗號分隔;任何不帶 =
號的值均假定為 redis 服務器端點。 如果未啟用 ssl,則沒有顯式端口的端點將使用 6379,而如果啟用 ssl,則將使用 6380。 以 $
開頭的令牌用於表示命令映射,例如:$config = cfg
。
過時的配置選項
為了向后兼容,這些選項在連接字符串中進行了解析(這意味着它們不會錯誤地視為無效),但是不再起作用。
Configuration string | ConfigurationOptions | Previous Default | Previous Meaning |
---|---|---|---|
responseTimeout={int} | ResponseTimeout | SyncTimeout | Time (ms) to decide whether the socket is unhealthy |
writeBuffer={int} | WriteBuffer | 4096 | Size of the output buffer |
Automatic and Manual Configuration
在許多常見方案中,StackExchange.Redis
自動配置很多設置,包括服務器類型和版本,連接超時以及主/副本關系。 但有時這命令已在 redis 服務器上禁用。在這種情況下,提供更多信息很有用:
ConfigurationOptions config = new ConfigurationOptions
{
EndPoints =
{
{ "redis0", 6379 },
{ "redis1", 6380 }
},
CommandMap = CommandMap.Create(new HashSet<string>
{ // EXCLUDE a few commands
"INFO", "CONFIG", "CLUSTER",
"PING", "ECHO", "CLIENT"
}, available: false),
KeepAlive = 180,
DefaultVersion = new Version(2, 8, 8),
Password = "changeme"
};
等效於命令字符串:
redis0:6379,redis1:6380,keepAlive=180,version=2.8.8,$CLIENT=,$CLUSTER=,$CONFIG=,$ECHO=,$INFO=,$PING=
Renaming Commands
redis 的一個不尋常的功能:可以禁用 和/或 重命名單個命令。按照前面的示例,這是通過 CommandMap
完成的,而不是將 HashSet<string>
傳遞給 Create()
(指示可用或不可用的命令),而是傳遞 Dictionary<string,string>
。假定字典中未提及的所有命令均已啟用且未重命名。空值或空白值表示該命令已禁用。例如:
var commands = new Dictionary<string,string> {
{ "info", null }, // disabled
{ "select", "use" }, // renamed to SQL equivalent for some reason
};
var options = new ConfigurationOptions {
// ...
CommandMap = CommandMap.Create(commands),
// ...
}
上面的內容等效於(在連接字符串中):
$INFO=,$SELECT=use
Twemproxy
Twemproxy 是一個工具,它允許使用多個 redis 實例,就好像它是單個服務器一樣,具有內置的分片和容錯能力(與 redis 群集非常相似,但是是單獨實現的)。Twemproxy 可用的功能集有所減少。 為了避免必須手動配置,可以使用 Proxy
選項:
var options = new ConfigurationOptions
{
EndPoints = { "my-server" },
Proxy = Proxy.Twemproxy
};
Tiebreakers and Configuration Change Announcements
通常,StackExchange.Redis 將自動解析主節點/副本節點。 但是,如果您未使用諸如 redis-sentinel 或 redis 集群之類的管理工具,則有時您會獲得多個主節點(例如,在重置節點進行維護時,它可能會重新顯示為網絡中的主節點)。為了解決這個問題,StackExchange.Redis 可以使用 tie-breaker 的概念:僅在檢測到多個主服務器時才使用(不包括 redis 集群,因為在此情況下應該有多個主服務器)。為了與 BookSleeve 兼容,默認使用名為 "__Booksleeve_TieBreak"
的鍵(始終在數據庫0中)。這被用作粗略的投票機制,以幫助確定首選的主控方,以便正確地路由工作。
同樣,當配置更改時(尤其是主/副本配置),對於連接的實例來說,使自己知道新情況(通過可用的 INFO
,CONFIG
等)也很重要。StackExchange.Redis 通過自動訂閱可以在其上發送此類通知的發布/訂閱頻道來實現。 由於類似的原因,此默認設置為 "__Booksleeve_MasterChanged"
。
可以通過 .ConfigurationChannel
和 .TieBreaker
配置屬性來自定義或禁用這兩個選項(設置為"")。
IServer.MakeMaster()
方法也使用這些設置,該方法可以在數據庫中設置 tie-breaker 並廣播配置更改消息。配置消息也可以單獨用於主/副本更改,僅通過 ConnectionMultiplexer.PublishReconfigure
方法來請求所有節點刷新其配置。
重新連接重試策略
當由於某種原因失去連接時,StackExchange.Redis
會自動嘗試在后台重新連接。它會一直重試,直到恢復連接為止。它將使用 ReconnectRetryPolicy
來決定兩次重試之間應等待的時間。ReconnectRetryPolicy
可以是線性(默認),指數或自定義重試策略。
示例:
config.ReconnectRetryPolicy = new ExponentialRetry(5000); // defaults maxDeltaBackoff to 10000 ms
//retry# retry to re-connect after time in milliseconds
//1 a random value between 5000 and 5500
//2 a random value between 5000 and 6050
//3 a random value between 5000 and 6655
//4 a random value between 5000 and 8053
//5 a random value between 5000 and 10000, since maxDeltaBackoff was 10000 ms
//6 a random value between 5000 and 10000
config.ReconnectRetryPolicy = new LinearRetry(5000);
//retry# retry to re-connect after time in milliseconds
//1 5000
//2 5000
//3 5000
//4 5000
//5 5000
//6 5000
原文地址:Configuration