Reputation: 3816
I am creating a REST service that has two methods one is GetAll and other is GetById.In my scenario, database request is very costly so i want to store output of GetAll somewhere (Cache) and use it for subsequent request GetById.
One of the characteristic of REST is it should be Statelessness. A request cannot be dependent on a past request and a service treats each request independently. I want to understand what should be ideal approach to handle such scenarios or how to design this requirement in REST?
Upvotes: 0
Views: 114
Reputation: 161783
The requirement for statelessness in REST is that the service should appear to be stateless. It doesn't matter if the service maintains some state internally. That's just an implementation detail.
Upvotes: 0
Reputation: 20033
The proper way to achieve what you want is by using caching, like MemoryCache
.
You create a separate, private function which fetches all the data and caches it in memory. Then you can have both GetAll
and GetById
use that function.
Your service will remain stateless.
MemoryCache
usage example
MemoryCache cache = MemoryCache.Default;
string cacheName = "MyCache";
if (!cache.Contains(cacheName) || cache[cacheName] == null)
{
// get data
var data = ...
// cache data
cache.Set(cacheName, data, new CacheItemPolicy() { SlidingExpiration = DateTime.Now.AddDays(1).TimeOfDay });
}
return cache[cacheName];
Upvotes: 2
Reputation: 2751
there are many solutions to this. one solution I would recommend you is the following:
configure infinispan to use it as a cache mechanism. inside there store a concurrent hashmap with key the query and with value the resultset of your database,
second time you want to getAll, check if the query exists as a key to your cache, if yes retrieve value from cache, else contact database and then insert the result in the cache.
Upvotes: 0