Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi.. Am new to this cache technique. My project contains videos , lot of images and some text data. Am getting all these data from database. It takes more time to load the data. how to implement cache for my webapplication. I googled for caching but i didnot understang how to put the queries in cache. please suggest me the way to implement cache. Am using struts.jsp and mysql Database for implementing web application.












Thanks In Advance
Posted

1 solution

Simply put, you are aiming to hold the data in memory and return that instead of reading from the persisted store.

As an example it is something like this:

Java
public Content getContent(Integer id)
{
  Content c;
  // first look for it in the cache defined as Map<integer,>
  if (cache.containsKey(id))
  {
    c = cache.get(id);
  }
  else
  {
    c = queryContent(id);
    cache.put(id, c);
  }
  return c;
}

private Content queryContent(Integer id)
{
  // actually go to the DB now and populate the content
  return contentFromDb;
}


This however has a problem. You eventually have EVERYTHING in memory. If you are considering a large amount of data then you'll need to consider flushing the cache. Normally you'd do this in a separate thread just going through all the items in the cache and either removing the oldest ones or reducing the size to a particular limit.

Either of these approaches need the content in the cache to be stamped, I use age and requests where I have implemented this with a formula that keeps anything requested if on average it is being called more than a given number of minutes:

Java
class Cache
{

  // stuff

  void flushCache(int maxMinutes)
  {
    List<integer> remove = HashList<>();
    for (Content c : cache.values())
    {
      if (c.isActive(maxMinites))
      {
        remove.add(c.getId());
      }
    }
    for (Integer i : remove)
    {
      cache.remove(i);
    }
  }
}

class Content
{
  bool isActive((int maxMinutes)
  {
    // age = minutes since instantiated
    // calls = number of times content was accessed
    if ((age / calls) <= maxMinutes)
    {
      return true;
    }
    return false;
}</integer>


Now, when the content is no longer not in use it is slowly removed.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900