Java 内存缓存数据

方式二:多容器存储

import java.util.Map;
import java.util.LinkedHashMap;

/**
 * @Title: GroupCacheFactory
 * @ProjectName leadeon-third
 * @Description: 容器创建工厂
 * @author: wangweitao
 * @date: 2019/3/15 10:24
 * @version: V1.0
 */
public class GroupCacheFactory {
    // 数据容器
    private Map<String, Object> container;   
public GroupCacheFactory() {
    container = new LinkedHashMap<>();
}

    /**
     * 如果组存在就返回,不存在就创建,保证不为null
     *
     * @param key
     * @return
     */
    public Group group(String key, int capacity) {
        Group group = null;
        Object entry = container.get(key);
        if (entry != null) {
            group = (Group) entry;
        } else {
            group = new Group(capacity);
            container.put(key, group);
        }

        return group;
    }

    /**
     * 如果组存在就返回,不存在就创建,默认容量(自行设置)
     *
     * @param key
     * @return
     */
    public Group group(String key) {

        return this.group(key, 300);
    }

}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Title: Group
 * @ProjectName leadeon-third
 * @Description: 容器数据处理工具类
 * @author: wangweitao
 * @date: 2019/3/15 10:24
 * @version: V1.0
 */
public class Group {

    private ArrayBlockingQueue<CacheEntity> queue;// 缓存队列

    private Integer capacity;

    public Group(int capacity) {
        queue = new ArrayBlockingQueue<CacheEntity>(capacity);
        this.capacity = capacity;
    }

    /**
     * 尾部进
     *
     * @param object
     * @param second
     */
    public void push(String key, Object object, int second) {

        // 放入队列,
        queue.offer(new CacheEntity(key, object, System.currentTimeMillis(), second, this));
    }

    /**
     * 尾部进
     *
     * @param object
     */
    public void push(String key, Object object) {

        push(key, object, 0);
    }

    /**
     * 返回并移除头部出
     *
     * @return
     */
    public Object poll() {

        CacheEntity entity = queue.poll();
        // 如果有效期超过,返回null
        if (!entity.isExpire()) {
            return null;
        }
        return entity.getValue();
    }

    /**
     * 返回头部元素并放到末尾
     *
     * @return
     */
    public Object rPoll() {

        CacheEntity entity = queue.poll();
        // 如果有效期超过,返回null
        if (!entity.isExpire()) {
            return null;
        }
        Object object = entity.getValue();
        queue.offer(entity);
        return object;
    }

    /**
     * 通过key寻找有效的缓存实体
     *
     * @param key
     * @return
     */
    private CacheEntity find(String key) {

        synchronized (queue) {
            Iterator<CacheEntity> iterator = queue.iterator();
            while (iterator.hasNext()) {
                CacheEntity entity = iterator.next();
                if (key.equals(entity.getKey())) {
                    return entity;
                }
            }
            return null;
        }
    }

    /**
     * 删除key
     *
     * @param key
     */
    public void delete(String key) {

        synchronized (queue) {
            CacheEntity entity = find(key);
            if (entity != null) {
                queue.remove(entity);
            }
        }
    }

    /**
     * 根据key获取
     *
     * @param key
     * @return
     */
    public Object getValue(String key) {

        CacheEntity entity = find(key);
        if (entity != null && entity.isExpire()) {
            return entity.getValue();
        }

        return null;
    }

    /**
     * 获取有效的缓存实体
     *
     * @return
     */
    private List<CacheEntity> getCacheEntitys() {

        List<CacheEntity> keys = new ArrayList<CacheEntity>();
        Iterator<CacheEntity> iterator = queue.iterator();
        while (iterator.hasNext()) {
            CacheEntity cacheEntity = iterator.next();
            if (cacheEntity.isExpire()) {
                keys.add(cacheEntity);
            }
        }
        return keys;
    }

    /**
     * 获取key列表
     *
     * @return
     */
    public List<String> getKeys() {

        List<String> keys = new ArrayList<String>();
        List<CacheEntity> caches = getCacheEntitys();
        for (CacheEntity cacheEntity : caches) {
            keys.add(cacheEntity.getKey());
        }
        return keys;
    }

    /**
     * 获取值列表
     *
     * @return
     */
    public List<Object> getValues() {

        List<Object> values = new ArrayList<Object>();
        List<CacheEntity> caches = getCacheEntitys();
        for (CacheEntity cacheEntity : caches) {
            values.add(cacheEntity.getValue());
        }
        return values;
    }

    /**
     * 查看元素存活时间,-1 失效,0 长期有效
     *
     * @param key
     * @return
     */
    public int ttl(String key) {

        CacheEntity entity = find(key);
        if (entity != null) {
            return entity.ttl();
        }
        return -1;
    }

    /**
     * 返回头部的元素
     *
     * @return
     */
    public Object peek() {

        CacheEntity entity = queue.peek();
        if (entity != null) {
            return entity.getValue();
        }
        return null;
    }

    /**
     * 设置元素存活时间
     *
     * @param key
     * @param second
     */
    public void expire(String key, int second) {

        CacheEntity entity = find(key);
        if (entity != null) {
            entity.setTimestamp(System.currentTimeMillis());
            entity.setExpire(second);
        }
    }

    /**
     * 查看key是否存在
     *
     * @param key
     * @return
     */
    public boolean exist(String key) {

        return find(key) != null;
    }

    /**
     * 查看组是否为空
     *
     * @return
     */
    public boolean isEmpty() {

        return queue.isEmpty();
    }

    /**
     * 获取存活元素的大小
     *
     * @return
     */
    public int size() {

        return getCacheEntitys().size();
    }

    /**
     * 获取容量
     *
     * @return
     */
    public Integer getCapacity() {

        return capacity;
    }
}
import java.io.Serializable;

/**
 * @Title: CacheEntity
 * @ProjectName leadeon-third
 * @Description: 缓存工具实体
 * @author: wangweitao
 * @date: 2019/3/15 10:26
 * @version: V1.0
 */
public class CacheEntity implements Serializable {

    private static final long serialVersionUID = -7404787588856658491L;

    private String key; // key

    private Object value;// 值

    private Long timestamp;// 缓存的时候存的时间戳,用来计算该元素是否过期

    private int expire = 0; // 默认长期有效

    private Group group;// 容器

    public CacheEntity(String key, Object value, Long timestamp, int expire, Group group) {
        super();
        this.key = key;
        this.value = value;
        this.timestamp = timestamp;
        this.expire = expire;
        this.group = group;
    }

    public void setTimestamp(Long timestamp) {

        this.timestamp = timestamp;
    }

    public Long getTimestamp() {

        return timestamp;
    }

    public String getKey() {

        return key;
    }

    public void setKey(String key) {

        this.key = key;
    }

    public Object getValue() {

        return value;
    }

    public void setValue(Object value) {

        this.value = value;
    }

    public int getExpire() {

        return expire;
    }

    public void setExpire(int expire) {

        this.expire = expire;
    }

    /**
     * 获取剩余时间
     *
     * @return
     */
    public int ttl() {

        if (this.expire == 0) {
            return this.expire;
        }
        return this.expire - getTime();
    }

    /**
     * 获取当前时间和元素的相差时间
     * @return
     */
    private int getTime() {

        if (this.expire == 0) {
            return this.expire;
        }
        Long current = System.currentTimeMillis();
        Long value = current - this.timestamp;
        return (int) (value / 1000) + 1;
    }

    /**
     * 是否到期
     *
     * @return
     */
    public boolean isExpire() {

        if (this.expire == 0) {
            return true;
        }
        if (getTime() > this.expire) {
            // 失效了就移除
            group.delete(key);
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "CacheEntity{" +
                "key='" + key + '\'' +
                ", value=" + value +
                ", timestamp=" + timestamp +
                ", expire=" + expire +
                ", group=" + group +
                '}';
    }
}
import org.springframework.web.bind.annotation.*;

/**
 * @Title: CacheTest
 * @ProjectName leadeon-third
 * @Description: 缓存测试
 * @author: wangweitao
 * @date: 2019/3/15 10:23
 * @version: V1.0
 */
@RestController
@RequestMapping(path = "/cache2")
public class CacheTest {

    // 创建一个工厂,暂时不支持持久化
    GroupCacheFactory factory=new GroupCacheFactory();
    // 获取一个组
    Group group1=factory.group("group1");

    @GetMapping("/set")
    public String setCache(){
        String value = "{\" hitemperature\":\"0\",\" lotemperature\":\"20\",\"weather\":\"阵雨\",\"weathersign\":\"http://clientdispatch.10086.cn:8080/group1/M00/00/A3/rBCJYVd2NiaAWmFNAADQT5AGIH8336.jpg\",\"weatherbluesign\":\"http://clientdispatch.10086.cn:8080/group1/M00/00/A3/rBCJYVd2NiaAWmFNAADQT5AGIH8336.jpg\"}";
        for (int i = 0;i<=200; i++){
            group1.push("001"+i,value+i,300);
        }
        return "数据缓存成功";
    }

    @PostMapping("/setValue")
    public String setValue(){
        String value = "{\" hitemperature\":\"0\",\" lotemperature\":\"20\",\"weather\":\"阵雨\",\"weathersign\":\"http://clientdispatch.10086.cn:8080/group1/M00/00/A3/rBCJYVd2NiaAWmFNAADQT5AGIH8336.jpg\",\"weatherbluesign\":\"http://clientdispatch.10086.cn:8080/group1/M00/00/A3/rBCJYVd2NiaAWmFNAADQT5AGIH8336.jpg\"}";
        group1.push("001500",value,300);
        return "数据缓存成功";
    }

    @PostMapping("/get")
    public Object getCache(@RequestBody String count){
        group1.getValue("001"+count);
        System.out.println(group1.getValue("001"+count));
        return group1.getValue("001"+count);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值