Spring 4, sharing cache beetwen nodes
Solution 1
I'll pick up your term "shared cache", which stands for a clustered or distributed cache product like, for example, Infinispan, hazelcast or Apache Ignite.
You may want a shared cache for the following reasons:
Consistency: If your application updates the cache in one node, a shared cache would care about the propagation of the update and ensure that every node sees the new value after the update is finished. This is something a shared cache can give you, but not necessarily any "shared cache" product will do.
Times 10 problem: When you add up more nodes a shared cache will limit the requests to the external service, otherwise, each node might request the identical value.
Big data: This applies to a distributed cache: You can cache more data then there is space in one system.
But you get this benefits at the cost of additional configuration and deployment complexity. Also the access latency to a shared cache, is usually much higher then for a local cache. For a comparison take a look at these benchmarks.
Wrap up: You have two nodes now. If you don't have the problem of a coordinated update or invalidation, stay with a simple local cache. If you want to be future proof and have spare time to tinker with shared caches, go for it :)
Solution 2
Since you are already using spring boot I'd use the build in Cache abstraction (annotation) using Redis in the background. Redis can be easily shared and clustered and is performant enough. See official documentation
user3528733
Updated on June 04, 2022Comments
-
user3528733 almost 2 years
We have Spring boot application on two nodes. Now we want to keep some data in cache instead of call external service every 5 sec. The question is how to share cache between two nodes? Is it possible ? Or maybe create two seperates caches once per node ? Which approach is better ? I suppose that maintaing shared cache is quite hard. Thanks for any tips
-
Nazaret K. almost 8 yearsYou could use Ehcache configured for clustering.
-
user3528733 almost 8 yearsdo I need another server for ehcache ?
-
Nazaret K. almost 8 yearsNo, it's just a library that you can embed in your application. Not even a separate process.
-
-
user3528733 almost 8 yearsOk, but do I need another machine to install redis ?
-
daniel.eichten almost 8 yearsWell if you want to be fault tolerant you'll need to install Redis on multiple machines and set up a HA cluster (redis.io/topics/cluster-tutorial). If you can do this on the same machine on which you are running your application depends on the requirements for security as well as if you have enough capacity left.