简单的本地缓存示例

1、缓存工具类(含新增缓存、删除缓存、缓存过期)

package com.org.cash;

import java.io.ObjectInputStream.GetField;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Cache {

    private final static Map<String, Entity> map = new HashMap<String, Entity>();
    
    //定时器线程池,用于清除过期缓存
    private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    
    /**
     * 添加缓存
     */
    public synchronized static void put(String key,Object data){
        Cache.put(key, data, 0);
    }
    
    
    /**
     * 添加缓存,含过期时间
     */
    
    public synchronized static void put(String key,Object data,long expire){
        Cache.remove(key);
        if (expire > 0) {
            //执行异步线程
            Future future = executor.schedule(new Runnable() {
                
                @Override
                public void run() {
                    //过期后清除该键值对
                    synchronized (Cache.class) {
                        map.remove(key);
                    }
                    
                }
            }, expire, TimeUnit.MILLISECONDS);
            map.put(key, new Entity(data, future));
        }else {
            map.put(key, new Entity(data, null));
        }
    }
    
    /**
     * 读取缓存;根据key值
     */
    public synchronized static Object get(String key){
        Entity entity = map.get(key);
        return entity == null?null:entity.getValue();
    }
    
    /**
     * 读取缓存,根据key值;和对象类型
     */
    public synchronized static<T> T get(String key,Class<T> clazz){
        return clazz.cast(Cache.get(key));
        
    }
    
    
    /**
     * 清除缓存
     */
    
    public synchronized static Object remove(String key){
        Entity entity = map.remove(key);
        if (entity == null) return null;
        
        //清除原键值对定时器
        Future future = entity.getFuture();
        
        if (future != null) future.cancel(true);
        return entity.getValue();
                
    }
    
    /**
     * 查询当前缓存的键值对数量
     */
    public synchronized static int size(){
        return map.size();
    }
    
    
}
2、缓存对象设置:

package com.org.cash;

import java.util.concurrent.Future;

public class Entity {

    private Object value;
    
    private Future future;

    public Entity(Object value, Future future) {
        super();
        this.value = value;
        this.future = future;
    }

    //获取值
    public Object getValue(){
        return value;
    }
    
    /**
     * 获取Future对象
     */
    public Future getFuture(){
        return future;
    }
    
}
 

3、测试类:

package com.org.cash;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CacheTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        String key = "id";
        
        //不设置过期时间
        Cache.put(key,123);
        System.out.println("key:"+key+",value:"+Cache.get(key));
        
        System.out.println("key:"+key+",value:"+Cache.remove(key));
        
        
        System.out.println("key:"+key+",value:"+Cache.get(key));
        
        
        //设置过期时间
        Cache.put(key, "123456",10000);
        System.out.println("key:"+key+",value:"+Cache.get(key));
        Thread.sleep(12000);
        System.out.println("key:"+key+",value:"+Cache.get(key));
        
        /*******************并发性能测试********************/
        
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        
        Future[] futures = new Future[10];;
        
        
        /**************添加***************/
        {
            long start = System.currentTimeMillis();
            
            for (int i = 0; i < 10; i++) {
                futures[i] = executorService.submit(()->{
                    for (int j = 0; j < 100000; j++) {
                        Cache.put(Thread.currentThread().getId()+key+j, j,300000);
                    }
                });
                
                
                
            }

            //等待全部线程执行完成,打印执行时间
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("添加耗时:%dms\n",System.currentTimeMillis()-start);
            
            //*******************查询*******************
            {
            long start2 = System.currentTimeMillis();
            
            for (int j = 0; j < 10; j++) {
                futures[j] = executorService.submit(()->{
                    for (int i = 0; i < 100000; i++) {
                        Cache.get(Thread.currentThread().getId()+key+i);
                        
                    }
                });
            }
            //等待全部线程执行完成,打印执行时间
            
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("查询耗时:%dms\n",System.currentTimeMillis()-start2);
            System.out.println("当前缓存容量:"+Cache.size());
            }
        }
        
    }
}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值