Dotnet
配置
因为有很多不同的方式来配置 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= | AbortOnConnectFail | true (false on Azure) | If true, Connect will not create a connection while no servers are available |
allowAdmin= | AllowAdmin | false | Enables a range of commands that are considered risky |
channelPrefix= | ChannelPrefix | null | Optional channel prefix for all pub/sub operations |
connectRetry= | ConnectRetry | 3 | The number of times to repeat connect attempts during initial Connect |
connectTimeout= | ConnectTimeout | 5000 | Timeout (ms) for connect operations |
configChannel= | ConfigurationChannel | __Booksleeve_MasterChanged | Broadcast channel name for communicating configuration changes |
configCheckSeconds= | ConfigCheckSeconds | 60 | Time (seconds) to check configuration. This serves as a keep-alive for interactive sockets, if it is supported. |
defaultDatabase= | DefaultDatabase | null | Default database index, from 0 to databases - 1 |
keepAlive= | KeepAlive | -1 | Time (seconds) at which to send a message to help keep sockets alive (60 sec default) |
name= | ClientName | null | Identification for the connection within redis |
password= | Password | null | Password for the redis server |
user= | User | null | User for the redis server (for use with ACLs on redis 6 and above) |
proxy= | Proxy | Proxy.None | Type of proxy in use (if any); for example "twemproxy" |
resolveDns= | ResolveDns | false | Specifies that DNS resolution should be explicit and eager, rather than implicit |
serviceName= | ServiceName | null | Used for connecting to a sentinel master service |
ssl= | Ssl | false | Specifies that SSL encryption should be used |
sslHost= | SslHost | null | Enforces a particular SSL host identity on the server's certificate |
sslProtocols= | SslProtocols | null | Ssl/Tls versions supported when using an encrypted connection. Use ' |
syncTimeout= | SyncTimeout | 5000 | Time (ms) to allow for synchronous operations |
asyncTimeout= | AsyncTimeout | SyncTimeout | Time (ms) to allow for asynchronous operations |
tiebreaker= | TieBreaker | __Booksleeve_TieBreak | Key to use for selecting a server in an ambiguous master scenario |
version= | 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= | ResponseTimeout | SyncTimeout | Time (ms) to decide whether the socket is unhealthy |
writeBuffer= | 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
译文地址: https://www.cnblogs.com/liang24/p/13818713.html