How to abstract from two different cache implementations

I am planning to use distributed cache in my webapp load balanced. Therefore, I will try to abstract the common functionality between apache ehcache and memcached.

My goal is to make a simple configuration switch to choose the caching solution to use. Should I go the SPI route, for example? how are XML parsers connected?

0


source to share


3 answers


Off the top of my head ...

  • Create an interface using generic cache-related methods (add (), remove (), refresh () comes to mind as the most obvious).
  • Create implementations of this interface that use the desired cache ("MyEhCacheImplementation" and "MyMemCachedImplementation" or something like that).
  • Create a CacheFactory that returns some type of cache based on a simple value like Number, String, or enum. Don't forget to back up for the default implementation!
  • create a way to initialize this single value to initialize the factory, for example if you have a class that reads various parameters during startup or you are using Spring applicationContext.xml or something similar, you need to create an initialization method for your cache that takes one parameter, calls the factory and returns the correct cache type and / or sets it to someplace where you are using it from.


I believe all you need is constructive to make it work reliably and so you can extend it whenever you want.

+1


source


After fixing the interface, this is really a template creation problem. Dependency Injection is my favorite, if your cache selection strategy is dynamic, you can use spring bean factories to solve at runtime. spring has support for "session" scopes in web applications, allowing the factory to resolve per session if you want.

If not, a simple service locator should do the trick as well.



http://en.wikipedia.org/wiki/Service_locator_pattern

+1


source


Spring also has a cache provider module that does exactly what you want to do. I'm just not sure if memcached is supported. Even if it isn't, writing an adapter for it can be less work than porting your own interface. See https://springmodules.dev.java.net/docs/reference/0.8/html_single/#cache

+1


source







All Articles