Reputation: 75
builder.register<IRedisClientsManager>(c => new PooledRedisClientManager(conection));
redis.GetCacheClient();
to set a cache entry I am doing:
cache_client.Set<T>(generate_key<T>(key), values, TimeSpan.FromSeconds(ttl.Value));
To get a cache entry I am doing:
using (var read_only_client = this.redis.GetReadOnlyClient())
{
return read_only_client.GetValue(generate_key<T>(key));
}
ISSUE => I am getting invalid cache values malformed JSON and misplaced text.
QUESTION => the reason I am getting invalid cache values is because I need to use Redis locks before setting or getting a cache value????
Upvotes: 2
Views: 249
Reputation: 143319
You'll rarely ever need to use RedisLocks which are for implementing a custom distributed locking. All Redis operations are atomic and if you need to send multiple operations atomically you can use either Redis Transactions or implement a LUA Script.
Without seeing the full Exception details or corrupted data, the issue is most likely reusing the same Redis Client instance across multiple threads. The IRedisClientsManager
is ThreadSafe and should be registered as a singleton, but the client instances it returns are not ThreadSafe and should not be shared amongst multiple threads, used as a singleton, stored in a static variable, etc.
To ensure proper usage each thread that uses them should resolve them and
using (var redis = redisManager.GetClient())
{
//...
}
Redis Client and Cache Registration Example
You should be registering both the IRedisClientsManager
and ICacheClient
as singletons, e.g:
container.Register<IRedisClientsManager>(c =>
new RedisManagerPool(connection));
container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient());
Given the Redis ICacheClient
is ThreadSafe the issue is in another area of your code where you're using the same Redis Instance across multiple threads. Make sure you carefully review all usages of Redis to ensure each Redis Client is properly disposed of and not shared amongst different threads.
If the issue continues despite proper usage of the library, please put together a stand-alone example project (e.g on GitHub) that we can run to see the issue and we'll review it.
Upvotes: 1