简单Java缓存类

本文介绍了一种基于Java的简易内存缓存实现方法,包括如何添加、读取、删除缓存数据以及设置缓存过期时间。通过示例代码展示了缓存的基本操作,并进行了性能测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求分析
项目中经常会遇到这种场景:一份数据需要在多处共享,有些数据还有时效性,过期自动失效。比如手机验证码,发送之后需要缓存起来,然后处于安全性考虑,一般还要设置有效期,到期自动失效。我们怎么实现这样的功能呢?

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;

/**
 * @Author: lixk
 * @Date: 2018/5/9 15:03
 * @Description: 简单的内存缓存工具类
 */
public class Cache {
    /**
     * 键值对集合
     */
    private final static Map<String, Entity> map = new HashMap<>();
    /**
     * 定时器线程池,用于清除过期缓存
     */
    private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 添加缓存
     *
     * @param key  键
     * @param data 值
     */
    public synchronized static void put(String key, Object data) {
        Cache.put(key, data, 0);
    }

    /**
     * 添加缓存
     *
     * @param key    键
     * @param data   值
     * @param expire 过期时间,单位:毫秒, 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));
        }
    }

    /**
     * 读取缓存
     *
     * @param key 键
     * @return
     */
    public synchronized static <T> T get(String key) {
        Entity entity = map.get(key);
        return entity == null ? null : (T) entity.value;
    }

    /**
     * 清除缓存
     *
     * @param key 键
     * @return
     */
    public synchronized static <T> T remove(String key) {
        //清除原缓存数据
        Entity entity = map.remove(key);
        if (entity == null) {
            return null;
        }
        //清除原键值对定时器
        if (entity.future != null) {
            entity.future.cancel(true);
        }
        return (T) entity.value;
    }

    /**
     * 查询当前缓存的键值对数量
     *
     * @return
     */
    public synchronized static int size() {
        return map.size();
    }

    /**
     * 缓存实体类
     */
    private static class Entity {
        /**
         * 键值对的value
         */
        public Object value;
        /**
         * 定时器Future
         */
        public Future future;

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

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: lixk
 * @Date: 2018/5/9 16:40
 * @Description: 缓存工具类测试
 */
public class CacheTest {

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        String key = "id";
        //不设置过期时间
        System.out.println("***********不设置过期时间**********");
        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));

        //设置过期时间
        System.out.println("\n***********设置过期时间**********");
        Cache.put(key, "123456", 1000);
        System.out.println("key:" + key + ", value:" + Cache.get(key));
        Thread.sleep(2000);
        System.out.println("key:" + key + ", value:" + Cache.get(key));

        System.out.println("\n***********100w读写性能测试************");
        //创建有10个线程的线程池,将1000000次操作分10次添加到线程池
        int threads = 10;
        ExecutorService pool = Executors.newFixedThreadPool(threads);
        //每批操作数量
        int batchSize = 100000;

        //添加
        {
            CountDownLatch latch = new CountDownLatch(threads);
            AtomicInteger n = new AtomicInteger(0);
            long start = System.currentTimeMillis();

            for (int t = 0; t < threads; t++) {
                pool.submit(() -> {
                    for (int i = 0; i < batchSize; i++) {
                        int value = n.incrementAndGet();
                        Cache.put(key + value, value, 300000);
                    }
                    latch.countDown();
                });
            }
            //等待全部线程执行完成,打印执行时间
            latch.await();
            System.out.printf("添加耗时:%dms\n", System.currentTimeMillis() - start);
        }

        //查询
        {
            CountDownLatch latch = new CountDownLatch(threads);
            AtomicInteger n = new AtomicInteger(0);
            long start = System.currentTimeMillis();
            for (int t = 0; t < threads; t++) {
                pool.submit(() -> {
                    for (int i = 0; i < batchSize; i++) {
                        int value = n.incrementAndGet();
                        Cache.get(key + value);
                    }
                    latch.countDown();
                });
            }
            //等待全部线程执行完成,打印执行时间
            latch.await();
            System.out.printf("查询耗时:%dms\n", System.currentTimeMillis() - start);
        }

        System.out.println("当前缓存容量:" + Cache.size());
    }
}


方法 作用
put(key, value) 插入缓存数据
put(key, value, expire) 插入带过期时间的缓存数据, expire: 过期时间,单位:毫秒
get(key) 获取缓存数据
remove(key) 删除缓存数据
size() 查询当前缓存记录数

//https://github.com/lixk?tab=repositories
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;

/**
 * simple memory cache
 *
 * @author lixk
 */
public class ECache {
  /**
   * key-value data set
   */
  private final static Map<String, Entity> DATA_BASE = new HashMap<>();
  /**
   * use scheduled executor to clean expired data
   */
  private final static ScheduledExecutorService CLEANER = Executors.newSingleThreadScheduledExecutor();

  /**
   * put data to cache
   *
   * @param key   unique identification for data
   * @param value your data
   */
  public synchronized static void put(String key, Object value) {
    ECache.put(key, value, 0L);
  }

  /**
   * put data to cache
   *
   * @param key    unique identification for data
   * @param value  your data
   * @param expire data survival time in milliseconds
   */
  public synchronized static void put(final String key, final Object value, final long expire) {
    //clean old data
    ECache.remove(key);
    //set schedule task
    if (expire > 0L) {
      Future future = CLEANER.schedule(new Runnable() {
        @Override
        public void run() {
          //remove data
          synchronized (ECache.class) {
            DATA_BASE.remove(key);
          }
        }
      }, expire, TimeUnit.MILLISECONDS);
      DATA_BASE.put(key, new Entity(value, expire, future));
    } else {
      DATA_BASE.put(key, new Entity(value, null, null));
    }
  }

  /**
   * read data from cache
   *
   * @param key unique identification for data
   * @return data bound to the key
   */
  public synchronized static <T> T get(String key) {
    Entity entity = DATA_BASE.get(key);
    if (entity != null && entity.isAlive()) {
      return (T) entity.value;
    }
    return null;
  }

  /**
   * remove cached data
   *
   * @param key unique identification for data
   * @return data bound to the key
   */
  public synchronized static <T> T remove(String key) {
    //remove data from data set
    Entity entity = DATA_BASE.remove(key);
    if (entity == null) {
      return null;
    }
    //cancel the schedule task
    if (entity.future != null) {
      entity.future.cancel(true);
    }

    return entity.isAlive() ? (T) entity.value : null;
  }

  /**
   * cached data entity
   */
  private static class Entity {
    Object value;
    Long expirationTime;
    Future future;

    Entity(Object value, Long expire, Future future) {
      this.value = value;
      this.expirationTime = (expire == null ? null : System.currentTimeMillis() + expire);
      this.future = future;
    }

    /**
     * Judging whether the entity is still alive
     *
     * @return boolean
     */
    boolean isAlive() {
      return this.expirationTime == null || this.expirationTime >= System.currentTimeMillis();
    }
  }
}

public class ECacheTest {
  public static void main(String[] args) throws InterruptedException {
    ECache.put("id", 123);
    Integer id = ECache.get("id");
    System.out.println(id);

    ECache.put("id", 123, 3000);
    id = ECache.get("id");
    System.out.println(id);
    Thread.sleep(3001);
    id = ECache.get("id");
    System.out.println("expired id:"+id);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值