自定义缓存学习

package cache;

/**
 * 缓存的实体类
 */
public class Cache {
    /*
    键
     */
    private String key;
    /*
    值
     */
    private Object value;
    /*
    缓存时间限制
     */
    private Long timeout;

    public void setKey(String key) {
        this.key = key;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public void setTimeout(Long timeout) {
        this.timeout = timeout;
    }

    public String getKey() {
        return key;
    }

    public Object getValue() {
        return value;
    }

    public Long getTimeout() {
        return timeout;
    }

    @Override
    public String toString() {
        return "Cache{" +
                "key='" + key + '\'' +
                ", value=" + value +
                ", timeout=" + timeout +
                '}';
    }
}
package cache;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CacheManagement{
    //定义一个Map,相当于缓存池
    private Map<String,Cache> cacheMap = new HashMap<String,Cache>();

    /**
     *放入的缓存内容会过期
     * @param key  缓存的key值
    * @param value  缓存的value值
     * @param timeout  缓存失效的时间间隔
     */
    public synchronized void put(String key,Object value, Long timeout){
        Cache cache = new Cache();
        cache.setKey(key);
        cache.setValue(value);
        if(null != timeout){
            //设置cache失效的时间点
            cache.setTimeout(System.currentTimeMillis()+timeout);
        }
        cacheMap.put(key,cache);
    }

    /**
     *放入的缓存内容不会过期
     * @param key  缓存的key值
     * @param cache  缓存的value值
     */
    public synchronized void put(String key,Object cache){
        put(key,cache,null);
    }

    /**
     * 删除某个缓存内容
     * @param key
     */
    public synchronized void del(String key){
        cacheMap.remove(key);
    }

    /**
     * 获取某个缓存值
     * @param key
     * @return
     */
    public synchronized Object get(String key){
        Cache cache = (Cache) cacheMap.get(key);
        if(null == cache){
            return null;
        }
        return cache.getValue();
    }

    /**
     * 定时删除过期缓存
     */
    public synchronized void scheduleDelExpired(){
        for (String key :cacheMap.keySet()) {
            Cache cache = cacheMap.get(key);
            if(null == cache){
                break;
            }
            Long timeout = cache.getTimeout();
            if(System.currentTimeMillis()-timeout > 0){
                del(key);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final CacheManagement cacheManagement = new CacheManagement();
        cacheManagement.put("username","sunny",5000L);
        System.out.println("保存完成");
        String username = (String) cacheManagement.get("username");
        System.out.println(username);


        /*
        开启线程,定期执行任务
         */
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        scheduledExecutorService.schedule(new Runnable() {
            public void run() {
                cacheManagement.scheduleDelExpired();
            }
        },5000,TimeUnit.MILLISECONDS);

        //模拟休息6秒中
        Thread.sleep(6000);
        System.out.println("删除之后");
        String username2 = (String) cacheManagement.get("username");
        System.out.println(username2);

    }


}
package cache;

import java.util.UUID;

/**
 * 生成Session的工具
 * 可以理解后台服务器往session中存值,客户端会需要拿jsessionId去获取session中存的东西
 */
public class SessionUtils {
    private static CacheManagement cacheManagement;

    /**
     * 初始化方法
     */
    private static void init(){
        if(null == cacheManagement){
            cacheManagement = new CacheManagement();
        }
    }

    /**
     * 存session
     * @param value
     * @return
     */
    public static String setAttribute(Object value){
        init();
        String jsessionId = UUID.randomUUID().toString();
        cacheManagement.put(jsessionId,value);
        return jsessionId;
    }

    /**
     * 通过sessionId获取session存的值
     * @param key
     * @return
     */
    public static Object get(String key){
        Object o = cacheManagement.get(key);
        if(null != o){
            return o;
        }
        return  null;
    }

    public static void main(String[] args) {
        Cache cache = new Cache();
        cache.setKey("username");
        cache.setValue("sunn");
        String s = SessionUtils.setAttribute(cache);
        System.out.println(SessionUtils.get(s));
    }
}

说明:

1、CacheManagement类理论情况上模拟的秒数应该和定时任务线程的延迟时间是相同的,这里主要想理解一下缓存的底层实现,加synchronized 是为了在main方法中验证时同步执行,然后能看出删除之后的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值