1. 程式人生 > >Java 自定義 物件快取

Java 自定義 物件快取

快取:把所有使用者的資料統一放到一個地方,為每個使用者的快取取一個名字來標示它,存的時候不要讓你的快取放上了別人的名字,取得時候不要讓你取了別人的名字的資料.這就要求你的執行緒做到執行緒同步.

效果圖:

圖片

程式碼:  

package com.kerun.app.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/** 
*@author qiyulin
*快取實現
*1.請求幾次後失效
*/
@SuppressWarnings("unchecked")
public class CacheManager {
//快取
@SuppressWarnings("unchecked")
private static HashMap cacheMap = new HashMap(); 

//請求幾次 去要新的
private static int num=10;//執行次數-----------0表示為開啟

private static int count=0;//計數-----和記錄當前的秒數

//單例項構造方法
private CacheManager() {
super();
}

//得到快取

public synchronized static Object getCache(String key) {
return (Object) cacheMap.get(key);
}

//判斷是否存在一個快取

public synchronized static boolean hasCache(String key) {
return cacheMap.containsKey(key);
}

//清除所有快取
public synchronized static void clearAll() {
cacheMap.clear();
}

//清除指定的快取
public synchronized static void clearOnly(String key) {
cacheMap.remove(key);
}

//載入快取
public synchronized static void putCache(String key, Object obj) {
cacheMap.put(key, obj);
}

//判斷快取是否終止
public  static boolean cacheExpired() {
System.out.println("次數"+count);
if(num==0){
return true;//終止使用快取
}else{
if(count>=num){
count=0;//重置count
return true;
}
count++;
System.out.println("---------------------------------------請求快取+"+count+"次數");
return false;
}

}

//獲取快取中的大小
public static int getCacheSize() {
return cacheMap.size();
}

//獲取快取物件中的所有鍵值名稱

public static ArrayList<String> getCacheAllkey() {
ArrayList a = new ArrayList();
try {
Iterator i = cacheMap.entrySet().iterator();
while (i.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
a.add((String) entry.getKey());
}
} catch (Exception ex) {} 
return a;
}

}


//實現

@Override
public List<Ship> listShip(int agentid) {
//獲取Ship下代理商的路由list
Map<String,Ship> map=listInactiveShip(agentid);
//獲取router中的路由list
List<String> macs=listRouterMac(agentid);
//相同mac 從ship的list中減去
if(!map.isEmpty()){
Set<String> keys=map.keySet();
Iterator<String> it=keys.iterator();
List<Ship> shiplist=new ArrayList<Ship>();
while(it.hasNext()){
//存在
String key=it.next();
if(!macs.isEmpty()){
//macs不為空
if(macs.contains(key)){//如果有了
//什麼都不做
}else{
Ship ship=map.get(key);
shiplist.add(ship);
}
}else{
//空把 200臺取出來
Ship ship=map.get(key);
shiplist.add(ship);
}
}
//放入快取-----------key一定是一個唯一的東西
CacheManager.putCache(""+agentid, shiplist);
//每次取出來都要放一次
return shiplist;
}
return null;
}

    @Override
public List<Ship> listShip(int agentid,int page, int limit) {
System.out.println("獲取快取大小"+CacheManager.getCacheSize());
List<Ship> all;
if(CacheManager.cacheExpired()){
//表示終止了
all=listShip(agentid);//重新拉取輸去
}else{
//判斷是否有該快取物件--執行緒同步獲取資料
if(CacheManager.hasCache(""+agentid)){
//存在
all=(List<Ship>) CacheManager.getCache(""+agentid);
}else{
//不存在
all=listShip(agentid);//重新拉取
}
}
//-----------------------------以上為獲取的資料---------------------------------
return all;
}