Redis Connection Strings
Redis Connection strings have been expanded to support the more versatile URI format which is now able to capture most of Redis Client settings in a single connection string (akin to DB Connection strings).
Redis Connection Strings supports multiple URI-like formats, from a simple hostname or IP Address and port pair to a fully-qualified URI with multiple options specified on the QueryString.
Some examples of supported formats:
localhost
127.0.0.1:6379
redis://localhost:6379
password@localhost:6379
clientid:password@localhost:6379
redis://clientid:password@localhost:6380?ssl=true&db=1
INFO
More examples can be seen in ConfigTests.cs
Any additional configuration can be specified as QueryString parameters. The full list of options that can be specified include:
Ssl | bool | If this is an SSL connection |
Db | int | The Redis DB this connection should be set to |
Client | string | A text alias to specify for this connection for analytic purposes |
Username | string | Redis Username when using ACLs |
Password | string | UrlEncoded version of the Password for this connection |
ConnectTimeout | int | Timeout in ms for making a TCP Socket connection |
SendTimeout | int | Timeout in ms for making a synchronous TCP Socket Send |
ReceiveTimeout | int | Timeout in ms for waiting for a synchronous TCP Socket Receive |
IdleTimeOutSecs | int | Timeout in Seconds for an Idle connection to be considered active |
NamespacePrefix | string | Use a custom prefix for ServiceStack.Redis internal index colletions |
When using Redis ACLs the Username needs to specified on the QueryString, e.g:
var connString = $"redis://{Host}?ssl=true&username={Username}&password={Password.UrlEncode()}";
var redisManager = new RedisManagerPool(connString);
ServiceStack.Redis SSL Support
ServiceStack.Redis supports SSL connections making it suitable for accessing remote Redis server instances over a secure SSL connection.
Specify SSL Protocol
Support for changing the Ssl Protocols used for encrypted SSL connections can be set on the connection string using the sslprotocols
modifier, e.g:
var connString = $"redis://{Host}?ssl=true&sslprotocols=Tls12&password={Password.UrlEncode()}";
var redisManager = new RedisManagerPool(connString);
using var client = redisManager.GetClient();
//...
Connecting to Azure Redis
As connecting to Azure Redis Cache via SSL was the primary use-case for this feature, we've added a new Getting connected to Azure Redis via SSL to help you get started.
Redis GEO
The release of Redis 3.2.0 brings it exciting new GEO capabilities which will let you store Lat/Long coordinates in Redis and query locations within a specified radius. To demonstrate this functionality we've created a new Redis GEO Live Demo which lets you click on anywhere in the U.S. to find the list of nearest cities within a given radius, Live Demo at: https://redis.netcore.io
Redis Client Managers
The recommended way to access RedisClient
instances is to use one of the available Thread-Safe Client Managers below. Client Managers are connection factories which should be registered as a Singleton either in your IOC or static class.
RedisManagerPool
With the enhanced Redis URI Connection Strings we've been able to simplify and streamline the existing PooledRedisClientManager
implementation and have extracted it out into a new clients manager called RedisManagerPool
.
In addition to removing all above options on the Client Manager itself, readonly connection strings have also been removed so the configuration ends up much simpler and more aligned with the common use-case:
container.Register<IRedisClientsManager>(c =>
new RedisManagerPool(redisConnectionString));
Pooling Behavior
Any connections required after the maximum Pool size has been reached will be created and disposed outside of the Pool. By not being restricted to a maximum pool size, the pooling behavior in RedisManagerPool
can maintain a smaller connection pool size at the cost of potentially having a higher opened/closed connection count.
PooledRedisClientManager
If you prefer to define options on the Client Manager itself or you want to provide separate Read/Write and ReadOnly
(i.e. Master and Replica) redis-servers, use the PooledRedisClientManager
instead:
container.Register<IRedisClientsManager>(c =>
new PooledRedisClientManager(redisReadWriteHosts, redisReadOnlyHosts) {
ConnectTimeout = 100,
//...
});
Pooling Behavior
The PooledRedisClientManager
imposes a maximum connection limit and when its maximum pool size has been reached will instead block on any new connection requests until the next RedisClient
is released back into the pool. If no client became available within PoolTimeout
, a Pool TimeoutException
will be thrown.
Read Only Clients
By default resolving a RedisClient with GetRedisClient()
or GetRedisClientAsync()
will return a client connected to the configured primary (master) host, if you also have replica (slave) hosts configured, you can access it with the GetReadOnlyClient()
or GetReadOnlyClientAsync()
APIs, e.g:
using var redisReadOnly = clientsManager.GetReadOnlyClient();
BasicRedisClientManager
If don't want to use connection pooling (i.e. you're accessing a local redis-server instance) you can use a basic (non-pooled) Clients Manager which creates a new RedisClient
instance each time:
container.Register<IRedisClientsManager>(c =>
new BasicRedisClientManager(redisConnectionString));
Accessing the Redis Client
Once registered, accessing the RedisClient is the same in all Client Managers, e.g:
var clientsManager = container.Resolve<IRedisClientsManager>();
using var redis = clientsManager.GetClient();
redis.IncrementValue("counter");
List<string> days = redis.GetAllItemsFromList("days");
//Access Typed API
var redisTodos = redis.As<Todo>();
redisTodos.Store(new Todo {
Id = redisTodos.GetNextSequence(),
Content = "Learn Redis",
});
var todo = redisTodos.GetById(1);
//Access Native Client
var redisNative = (IRedisNativeClient)redis;
redisNative.Incr("counter");
List<string> days = redisNative.LRange("days", 0, -1);
A more detailed list of the available RedisClient APIs used in the example can be seen in the C# interfaces below:
Pipeline & Transaction APIs
Generic Client APIs
Server Collection APIs
Async Redis
The async support in ServiceStack.Redis is designed for optimal efficiency and uses ValueTask
& other modern Async APIs only available in .NET Standard 2.0 and .NET Framework v4.7.2+ projects where there's async API equivalents for most sync APIs as contained within the Async Redis interfaces below:
Async Pipeline & Transaction APIs
- IRedisTransactionAsync
- IRedisPipelineSharedAsync
- IRedisQueueableOperationAsync
- IRedisQueueCompletableOperationAsync
Async Generic Client APIs
- IRedisTypedClientAsync
- IRedisHashAsync
- IRedisListAsync
- IRedisSetAsync
- IRedisSortedSetAsync
- IRedisTypedTransactionAsync
- IRedisTypedQueueableOperationAsync