Java Web Application: How to implement caching techniques?

前端 未结 6 2044
别那么骄傲
别那么骄傲 2020-12-12 18:16

I am developing a Java web application that bases it behavior through large XML configuration files that are loaded from a web service. As these files are not actually requi

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 18:55

    I did not had any problems with putting cached object instance inside ServletContext. Do not forget other 2 options (request scope, session scope) with setAttributes methods of this objects. Anything that is supported natively inside webcontainers and j2ee serveers is good (by good I mean it's vendor independed, and without heavy j2ee librarires like Spring). My biggest requirements is that servers gets up and running in 5-10 seconds.

    I really dislike all caching solution, beacuse it's so easy to get it working on local machine, and hard to get it working on production machines. EHCACHE, Infinispan etc.. Unless you need cluster wide replication / distribution, tightly integrated with Java ecosystem, you can use REDIS (NOSQL datatabase) or nodejs ... Anything with HTTP interface will do. Especially

    Caching can be really easy, and here is the pure java solution (no frameworks):

    import java.util.*;
    
    /*
      ExpirableObject.
    
      Abstract superclass for objects which will expire. 
      One interesting design choice is the decision to use
      the expected duration of the object, rather than the 
      absolute time at which it will expire. Doing things this 
      way is slightly easier on the client code this way 
      (often, the client code can simply pass in a predefined 
      constant, as is done here with DEFAULT_LIFETIME). 
    */
    
    public abstract class ExpirableObject {
      public static final long FIFTEEN_MINUTES = 15 * 60 * 1000;
      public static final long DEFAULT_LIFETIME = FIFTEEN_MINUTES;
    
      protected abstract void expire();
    
      public ExpirableObject() {
        this(DEFAULT_LIFETIME);
      }
    
      public ExpirableObject(long timeToLive) {
        Expirer expirer = new Expirer(timeToLive);
        new Thread(expirer).start();
      }
    
      private class Expirer implements Runnable {  
        private long _timeToSleep;
        public Expirer (long timeToSleep){
          _timeToSleep = timeToSleep;
        }
    
        public void run() {
          long obituaryTime = System.currentTimeMillis() + _timeToSleep; 
          long timeLeft = _timeToSleep;
          while (timeLeft > 0) {
            try {
              timeLeft = obituaryTime - System.currentTimeMillis();  
              if (timeLeft > 0) {
                Thread.sleep(timeLeft);
              } 
            }
            catch (InterruptedException ignored){}      
          }
          expire();
        }
      }
    }
    

    Please refer to this link for further improvements.

提交回复
热议问题