package com.gx.obe.server.common.cache; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; public class Group { private ArrayBlockingQueue queue;// 缓存队列 private Integer capacity; public Group(int capacity) { queue = new ArrayBlockingQueue(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); } /** * 返回有效的缓存实体 * * @param key * @return */ private CacheEntity find(String key) { synchronized (queue) { Iterator iterator = queue.iterator(); while (iterator.hasNext()) { CacheEntity entity = iterator.next(); if (key.equals(entity.getKey())) { return entity; } } return null; } } /** * 删除 * * @param key */ public void delete(String key) { synchronized (queue) { CacheEntity entity = find(key); if (entity != null) { queue.remove(entity); } } } /** * 获取数据 * * @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 getCacheEntitys() { List keys = new ArrayList(); Iterator iterator = queue.iterator(); while (iterator.hasNext()) { CacheEntity cacheEntity = iterator.next(); if (cacheEntity.isExpire()) { keys.add(cacheEntity); } } return keys; } /** * 查看元素存活时间,-1 失效,0 长期有效 * * @param key * @return */ public int ttl(String key) { CacheEntity entity = find(key); if (entity != null) { return entity.ttl(); } return -1; } /** * 设置元素存活时间 * * @param key * @param second */ public void expire(String key, int second) { CacheEntity entity = find(key); if (entity != null) { entity.setTimestamp(System.currentTimeMillis()); entity.setSeconds(second); } } /** * 查看是否存在 * * @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; } }