EzDev.org

CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. Cache Manager - Caching Framework for C# .NET cachemanager is an open source caching framework for .net written in c# and is available via nuget. it supports various cache providers and implements many advanced features.. with .net core support, cross platform c# .net


Using LoadingCache with CacheManager

I use next one for my custom cache manager:

SimpleCacheManager cacheManager = new SimpleCacheManager();
GuavaCache myCache = new GuavaCache("telescope", CacheBuilder.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES).build());
cacheManager.setCaches(Arrays.asList(myCache));
return cacheManager;

Now I want to use LoadingCache, because I need the method refreshAfterWrite(5, TimeUnit.MINUTES) instead of expireAfterWrite(5, TimeUnit.MINUTES).

I can't put LoadingCache to GuavaCache and then set this GuavaCache into SimpleCacheManager.

Which implementations I need to use?


Source: (StackOverflow)

CacheManager.Net - Redis pipelining

Can someone please confirm whether CacheManager.Net supports redis pipelining?

I could not find it in the documentation

Thanks a lot.

Cheers, U


Source: (StackOverflow)

CacheManager.net (Redis) - Cache.Add only supports hashes?

I've just begun playing around with CacheManager.Net to add distributed caching capabilities to our app. My level 2 cache is Redis and it seem to work fine.

I notice that when I do a Cache.Add(cacheItem), it always gets added as a Hash to redis. Using CacheManager, is it possible to add objects as other redis data types? Say as a "String"?

Thanks. U


Source: (StackOverflow)

How to Handle Multiple servers trying to clear the redis Database

I have four Severs connected to redis. When the redis server goes down and Comes up. I want to clear the redis database. Issue is that All the servers are firing the clear action. How to handle such that only one servers fires the clear and notifies to all other servers. I am using the StackExchange.Redis and CacheManager.Net Packages as redis client libraries


Source: (StackOverflow)

Register generic ICacheManager using an IoC container (Ninject)

This is for the CacheManager library by Michah Conrad. In his example, he creates a cache manager using the CacheFactory.Build method, as seen here:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        var container = new UnityContainer();
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        var cache = CacheFactory.Build("todos", settings =>
        {
            settings
                .WithSystemRuntimeCacheHandle("inprocess");
        });
        container.RegisterInstance(cache);
    }
}

My question, is it possible to register the ICacheManger interface so that any property dependencies of any type will be automatically created by the IoC container?

Say I have this class

public class MyClass
{
    [Inject]
    public ICacheManager<string> StringCacheManager { get; set; }

    [Inject]
    public ICacheManager<int> IntCacheManager { get; set; }
}

How could I set up my Ninject kernel to bind the generic ICacheManager interface so that it resolves using the types in MyClass?

Something like this, but that actually works:

kernel.Bind<ICacheManager<T>>().ToMethod((context) =>
{
    return CacheFactory.FromConfiguration<T>("defaultCache");
});

Source: (StackOverflow)

Should I cache json, Bson or JObject in the ICacheManager?

I have some JObjects which I need to cache, and I wonder what best practice is when caching such data in CacheManager?

I'm concerned with

  1. Using a reasonably small amount of memory in the cache.
  2. Not unnecessarily serialize to avoid useless processing.

If I cache the json string I need to parse it every time I read the cache.

If I cache the JObject I don't know how it will be serialized to the cache. Probably as a non-compact binary array. But I won't have to do anything to it after retrieving it.

That's why I'm considering that perhaps it will serialize Bson better, or maybe that's going to simply add another layer of serialization? After all, I'll have to convert the Bson to JObject when reading the cache, much like if I were to cache the json string.


Source: (StackOverflow)

Unit tests for modules using Play cache (Scala)

Looking for some guidance for unit testing a module using Play cache in Scala. I have a method which queries database, gets static data and stores in Play's cache. While writing unit tests the following error shows:

Error in custom provider, java.lang.IllegalStateException: The CacheManager has been shut down. It can no longer be used.

I do not have any tear down in my scala unit tests for this error to show up. Any advice as to why this is happening would be great.

Also, any suggestions for resolving this would by an eye-opener. One possible way I could think is having an additional parameter and enable/disable the cache depending on the parameter value for test/non-test workflows. But is that the only way. Should I pass a custom implementation of my cache just for my tests?


Source: (StackOverflow)

Redis Cluster configuration for CacheManager.NET

I have a basic question about Redis connection parameters from CacheManager.NET perspective. In case when we have Redis cluster with a master and 2 slaves, and with quorum of sentinel processes, should we provide the IP:PORT combinations pointing to the sentinel processes OR the actual Redis server processes.

As suggested in https://seanmcgary.com/posts/how-to-build-a-fault-tolerant-redis-cluster-with-sentinel, it is advisable to ask the sentinel process about the actual master before making the connection. And probably that goes in line with Jedis which provides JedisSentinelPool to do the initial lookup.

Essentially what we want is that the load balancing on reads (via CacheManager.NET) and the writes should go to the current master node of the cluster.


Source: (StackOverflow)

Using MemoryCacheHandle with RedisCacheBackplane but without RedisCacheHandle

On the documentation it says

    /// The cache manager must have at least one cache handle configured with <see cref="CacheHandleConfiguration.IsBackplaneSource"/> set to <c>true</c>.
    /// Usually this is the redis cache handle, if configured. It should be the distributed and bottom most cache handle.

I know how to do it with RedisCacheHandle, since it's given as example on Cachemanager's website

var cache = CacheFactory.Build<int>("myCache", settings =>
{
    settings
    .WithSystemRuntimeCacheHandle("inProcessCache")
    .And
    .WithRedisConfiguration("redis", config =>
    {
        config.WithAllowAdmin()
            .WithDatabase(0)
            .WithEndpoint("localhost", 6379);
    })
    .WithMaxRetries(1000)
    .WithRetryTimeout(100)
    .WithRedisBackplane("redis")
    .WithRedisCacheHandle("redis", true);
});

The problem is I don't want to use Redis as cache resource; I just want to make a distributed cache by the power of Redis Pub/Sub mechanism. According to my debugging through the code, by using Redis Backplane feature I'm able to send messages to and receive messages from Redis indeed. So why not use RedisCacheHandle and instead use SystemRuntimeCacheHandle?

So, my expectation was the successfull execution with the following cache configuration

var cache = CacheFactory.Build<int>("myCache", settings =>
{
    settings
    .WithSystemRuntimeCacheHandle("inProcessCache")
    .And
    .WithRedisConfiguration("redis", config =>
    {
        config.WithAllowAdmin()
            .WithDatabase(0)
            .WithEndpoint("localhost", 6379);
    })
    .WithMaxRetries(1000)
    .WithRetryTimeout(100)
    .WithRedisBackplane("redis")
    .WithSystemRuntimeCacheHandle("inProcessCache", true);
});

But it's not working. Can you please show me a solution? What am I doing wrong? Or, eventhough it's written in the documentation as

...Usually this is the redis cache handle...

are there any way to use the cache synchronization feature without RedisCacheHandle?

https://github.com/MichaCo/CacheManager/issues/111


Source: (StackOverflow)

Is it possible to use ICacheManager<> with different type of configurations at the same time?

Imagine that I have interfaces like below which all inherits from ICacheManager<>

public interface ICacheManagerRuntime<T> : ICacheManager<T>
public interface ICacheManagerRedis<T> : ICacheManager<T>
public interface ICacheManagerRedisWithRuntime<T> : ICacheManager<T>

I want to inject ICacheManager{CacheType} interfaces to implemantation of Cache classes like:

CacheRuntime, CacheRedis, CacheRedisWithRuntime

With unity I want to inject them like below:

container.RegisterType<ICacheManagerRuntime<object>>(
                new ContainerControlledLifetimeManager(),
                new InjectionFactory((c, t, n) =>
                {
                    return CacheFactory.Build... // Return CacheManager just with RuntimeCacheHandle
                })));


container.RegisterType<ICacheManagerRedis<object>>(
                new ContainerControlledLifetimeManager(),
                new InjectionFactory((c, t, n) =>
                 {
                    return CacheFactory.Build... // Return CacheManager just with RedisCacheHandle
                })));


container.RegisterType<ICacheManagerRedisWithRuntime<object>>(
                new ContainerControlledLifetimeManager(),
                 {
                    return CacheFactory.Build... // Return CacheManager just with RuntimeCacheHandleWithRedisBackPlane
                })));

What ever I have done, I am getting this exception:

An unhandled exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll

Additional information: Resolution of the dependency failed, type = "Solid.Play.Business.Interfaces.IProductService", name = "(none)".

Exception occurred while: Resolving parameter "cache" of constructor Solid.Play.Cache.Caches.CacheRuntime(Solid.Play.Cache.Interfaces.ICacheManagerRuntime`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] cache).

Exception is: InvalidCastException - Unable to cast object of type 'CacheManager.Core.BaseCacheManager`1[System.Object]' to type 'Solid.Play.Cache.Interfaces.ICacheManagerRuntime`1[System.Object]'.

-----------------------------------------------

At the time of the exception, the container was:



  Resolving Solid.Play.Business.Services.ProductService,(none) (mapped from Solid.Play.Business.Interfaces.IProductService, (none))

    Resolving Solid.Play.Cache.Interception.CachingInterceptorBehavior,(none)

    Resolving parameter "cache" of constructor Solid.Play.Cache.Interception.CachingInterceptorBehavior(Solid.Play.Cache.Interfaces.ICacheSolid cache)

      Resolving Solid.Play.Cache.Caches.CacheSolid,(none) (mapped from Solid.Play.Cache.Interfaces.ICacheSolid, (none))

      Resolving parameter "cacheRuntime" of constructor Solid.Play.Cache.Caches.CacheSolid(Solid.Play.Cache.Interfaces.ICacheRuntime cacheRuntime, Solid.Play.Cache.Interfaces.ICacheRedis cacheRedis, Solid.Play.Cache.Interfaces.ICacheRedisWithRuntime cacheRedisWithRuntime)

        Resolving Solid.Play.Cache.Caches.CacheRuntime,(none) (mapped from Solid.Play.Cache.Interfaces.ICacheRuntime, (none))

        Resolving parameter "cache" of constructor Solid.Play.Cache.Caches.CacheRuntime(Solid.Play.Cache.Interfaces.ICacheManagerRuntime`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] cache)

Source: (StackOverflow)

Using MichaCo\CacheManager with Redis4You and RedisLab redis server

https://github.com/MichaCo/CacheManager/issues/42

Hi. I'm using Redis4You hosted redis server. And the following configuration works fine. When the code comes to line Cache.Add("a", "b");, then it stucks there for an infinite time. When I monitor the Redis server I see the console with full of PING there.

static class Program
{
    static readonly ICacheManager<string> Cache = CacheFactory.Build<string>("Test", cbcp =>
    {
        cbcp.WithSystemRuntimeCacheHandle("testCache")
            .And
            .WithRedisConfiguration("redis", rcb =>
            {
                rcb.WithEndpoint("<XXX>", 1111)
                   .WithPassword("<YYY>")
                   .WithAllowAdmin()
                   .WithDatabase(1);
            })
            .WithMaxRetries(100)
            .WithRetryTimeout(10)
            .WithRedisBackPlate("redis")
            .WithRedisCacheHandle("redis", true);
    });
    static void Main(string[] args)
    {
        /* It stucks in the first line. */
        Cache.Add("a", "b");
        Console.ReadLine();
    }
}

I debugged the code and the LuaScripts provided by CacheManager library such as the one below causes an error:

local result=redis.call('HMSET', KEYS[1], 'value', ARGV[1], 'type', ARGV[2], 'expiration', ARGV[3], 'timeout', ARGV[4], 'created', ARGV[5])
if ARGV[3] ~= '0' and ARGV[4] ~= '0' then
    redis.call('PEXPIRE', KEYS[1], ARGV[4])
else
    redis.call('PERSIST', KEYS[1])
end
return result

... and this luascript is used on this part of code in CacheManager library RedisCacheHandler.cs LoadScripts() method;

var putLua = StackRedis.LuaScript.Prepare(ScriptPut);
putLua.Load(server);

So, What is the problem here? (I don't think it's the version because redis4you uses 2.4 and redislab uses 3.0.3 of redis.)


Source: (StackOverflow)

CacheManager memcached configuration

I'm going to use CacheManager for my .net project. The problem is that I can't find any examples of CacheManager.Memcached usage.

This is how I use it:

public class GlobalCache
{
     private static ICacheManager<object> memcachedClient { get; set; }

     private static readonly object locker = new object();

     static GlobalCache()
     {
          if (memcachedClient == null)
          {
               lock (locker)
               {
                  memcachedClient = CacheFactory.Build("memcached", settings => settings.WithMemcachedCacheHandle("memcached"));
               }
          }
     }
}

Web.config:

   <configuration>
     <enyim.com>
       <memcached protocol="Binary">
         <servers>
           <add address="127.0.0.1" port="11211" />
         </servers>
       </memcached>
     </enyim.com>

     <cache name="memcached">
        <handle name="memcached"/>
     </cache>
   </configuration>

The error I have is: http://c2n.me/3hSHqvR.png - unknown section in web config.

If I remove all these sections, I have another runtime error: http://c2n.me/3hSI745.png - config error.

I tried to use settings.WithSystemRuntimeCacheHandle() instead of settings.WithMemcachedCacheHandle() and it works fine without any config sections. But in this case, my cache is cleared every time I restart my app. And what I want is - store cache in memcached storage, without any relation to my application.

So if you have some examples or small tutorial of how to use memcached with CacheManager - I will be much appreciated.

Thanks in advance!


Source: (StackOverflow)

cachemanager.net - How to get List of objects from redis cache based on key passed?

How do I get a List of objects from redis cache based on the key passed?

I am exploring cachemanager.net for redis cache. I have gone through the examples. But I could not find any example related to getting the List of objects based on the key passed.

var lst =cache.Get("Key_1");

It is returning only one object.

But I would like it like this. I have stored 1000 objects in cache with key name like Key_1, Key_2, Key_3..... Key_1000. I want to get list of 1000 objects if I pass Key_* as Key.


Source: (StackOverflow)

Using MichaCo\CacheManager with Redis

I'm looking to using MichaCo\CacheManager with Redis. Although the project page mentions that distributed cache with Redis is supported. But I do not see any examples of Redis configuration, setting up the environment etc. Anyone have experience with using this library with Redis in their project? Any tips would be appreciated.


Source: (StackOverflow)

How to find the redis is up after it went down

Suppose due to network failure redis went down for some time . How will i figure out after it up. Is there any event that i can subscribe in the Client (StackExchange.Redis ) so that it notifies me?


Source: (StackOverflow)