Java三個類實現記憶體緩衝

來源:互聯網
上載者:User

有一個需求,本來打算用redis來做,但是發現redis的list不支援某一項逾時設定,

所以就用java自己寫了一個簡單的緩衝,操作類似redis,總共只有3個類:

項目地址:https://github.com/newpanjing/group-cache.git

項目名:group-cache

簡單的記憶體緩衝實現,實現group概念,一個group裡面是個有序的集合,集合支援key-value expire彌補redis list的不足 總共有3個類: GroupCacheFactory 工廠用於擷取Group Group 組,存放多個key和value CacheEntity 緩衝實體,所有緩衝的資料都是以CacheEntity為載體放入Group中 測試代碼:

package com.qikenet.cache;import java.util.Random;public class CacheTest {public static void main(String[] args) {    /**     * 概念:     * 組緩衝,在傳統redis、memcached 這一類的緩衝容器中,都是key-value類型的     * 所謂的組緩衝,就是在key-value的外層加一個標識     * 用list來做比較,在redis中,list的結構是這樣的,並且list的某一項不能設定存活時間:     *  abc     *      1     *      2     *      3     *      * 在GroupCache中結構是這樣的   :     * abc     *  a 1 10     *  b 2 5     *  c 3 1     * 第一行:a代表key,1代表value,10代表存活10秒,存活時間以秒為單位              */    //建立一個工廠,暫時不支援持久化    GroupCacheFactory factory=new GroupCacheFactory();    //擷取一個組    Group group1=factory.group("group1");    group1.push("a", 123);//預設永久存活    group1.push("b", 321, 10);//存活10秒    //查看還有多久失效    System.out.println("group 1 的元素b 剩餘失效時間:"+group1.ttl("b"));    //檢測值是否存在    System.out.println("a是否存在:"+group1.exist("a"));    System.out.println("c是否存在:"+group1.exist("c"));    //擷取有效key    System.out.println("group1 keys:"+group1.getKeys());    //擷取有效value    System.out.println("group1 values:"+group1.getValues());    //通過key擷取值    System.out.println("通過a擷取:"+group1.getValue("a"));    //擷取一個組,並設定容量為100,預設容量為1000,不同的group中資料不能共用    Group group2=factory.group("group2",100);    //如果push的資料大於容量,則會丟棄    for(int i=0;i<101;i++){        group2.push(String.valueOf(i), i, new Random().nextInt(10));    }    //擷取存活的元素的數量    System.out.println("group2大小:"+group2.size());    //設定元素的存活時間    group2.expire("2", 100);    //刪除一個元素    group2.delete("3");    System.out.println("group刪除後的元素大小:"+group2.size());    //擷取group容量大小    System.out.println("group2容量:"+group2.getCapacity());    System.out.println(group2.getKeys());}}



具體代碼:

緩衝工廠:

package com.qikenet.cache;import java.util.LinkedHashMap;import java.util.Map;import java.util.Random;/** * 簡單的記憶體緩衝實現,實現group概念,<br/> * 一個group裡面是個有序的集合,<br/> * 集合支援key-value expire彌補redis list的不足 *  * @author panjing * @date 2016年8月6日 上午9:27:22 * @project qikenet-group-cache */public class GroupCacheFactory {// 資料容器private Map<String, Object> container;public GroupCacheFactory() {container = new LinkedHashMap<String, Object>();}/** * 如果組存在就返回,不存在就建立,保證不為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;}/** * 如果組存在就返回,不存在就建立,預設容量1000 *  * @param key * @return */public Group group(String key) {return this.group(key, 1000);}}

緩衝Group:

package com.qikenet.cache;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;/** * 組操作,內部資料有序隊列 *  * @author panjing * @date 2016年8月6日 上午9:33:34 * @project qikenet-group-cache * @param <T> */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();// 如果有效期間超過,返回nullif (!entity.isExpire()) {return null;}return entity.getValue();}/** * 返回頭部元素並放到末尾 *  * @return */public Object rPoll() {CacheEntity entity = queue.poll();// 如果有效期間超過,返回nullif (!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;}}
緩衝實體:

package com.qikenet.cache;import java.io.Serializable;/** * 緩衝實體 *  * @author panjing * @date 2016年8月6日 上午9:33:25 * @project qikenet-group-cache */public class CacheEntity implements Serializable {private static final long serialVersionUID = 2082223810638865724L;private String key; // keyprivate 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;}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.