工程中用到的缓存方法

自定义的缓存方法,这种缓存方法只在第一次访问时慢

action中使用下面方法调用缓存:

channel = channelManager.preCacheGetChannel(style, "INDEX","index");

 

ChannelManagerImpl:

private static final long MAX_FRESH_TIME = 60 * 1000;//1min

private static final int FIXED_CACHE_SIZE = 1000; //缓存的大小

 

public Channel preCacheGetChannel(String style, String channelType,

String cacheKey) {

//用三个属性拼出key

       String key = new StringBuilder()

       .append("style:" + style)

       .append(";channelType:" + channelType)

       .append(";cacheKey:" + cacheKey)

       .toString();

       //获取缓存后的channel

       PreCacheChannel pchannel = PRE_CACHE_MAP.get(key);

       //如果没有缓存则新建一个缓存

if(pchannel == null) {

           //获取真正的channel

           Channel channel = getChannel(style, channelType);

           //channel的所有属性放到copy一个新的channel

           Channel copy = copyOfChannel(channel);

           pchannel= new PreCacheChannel(MAX_FRESH_TIME);

           pchannel.setChannel(copy);

           pchannel.setLastRefreshTime(System.currentTimeMillis());

           pchannel.setOnLoading(false);

           PRE_CACHE_MAP.put(key, pchannel);

       } else if (!pchannel.isFresh()) {

           preLoading(style, channelType, key, pchannel);

       }

    return pchannel.getChannel();

}

 

 

private static final Map<String, PreCacheChannel> PRE_CACHE_MAP = Collections.synchronizedMap(     //获取一个线程安全的map

new LinkedHashMap<String, PreCacheChannel>(FIXED_CACHE_SIZE, 1.1f, true) {

    @Override

    protected boolean removeEldestEntry(

           Map.Entry<String, PreCacheChannel> eldest) {

              if (this.size() >= FIXED_CACHE_SIZE) {

                  return true;

              }

              return false;

           }

    });

 

 

 

class PreCacheChannel {

       Channel channel;

       long lastRefreshTime;

       volatile boolean onLoading;

       long maxFreshTime;

             

       /**

        * @param maxFreshTime

        */

       public PreCacheChannel(long maxFreshTime) {

           super();

           this.maxFreshTime = maxFreshTime;

       }

       /**

        * 默认构造函数

        */

       public PreCacheChannel() {

           super();

       }

       /**

       *是否超过缓存时间

       */

       public boolean isFresh() {

           return System.currentTimeMillis() - lastRefreshTime < maxFreshTime;

       }

    。。。。。。。。。//getter and setter

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值