java設置緩存
java有自己的緩存輸入輸出類,比如 InputStream,FileOutputStram等 具體可以查看API,
要想自己實現的話,很簡單,設置一個足夠大的位元組數組就可以了,把需要的東西放進去,就是個緩存。
⑵ java中如何配置2級緩存
Hibernate的二級緩存同一級緩存一樣,也是針對對象ID來進行緩存。所以說,二級緩存的作用范圍是針對根據ID獲得對象的查詢。
● 在執行各種條件查詢時,如果所獲得的結果集為實體對象的集合,那麼就會把所有的數據對象根據ID放入到二級緩存中。
● 當Hibernate根據ID訪問數據對象的時候,首先會從Session一級緩存中查找,如果查不到並且配置了二級緩存,那麼會從二級緩存中查找,如果還查不到,就會查詢資料庫,把結果按照ID放入到緩存中。
● 刪除、更新、增加數據的時候,同時更新緩存。
⑶ java怎麼將數據放入緩存
java放入session緩存中
方法如下:
session.setAttribute("Name",Value);
Name 隨便取,value就是要放的數據
獲取的時候session.getAttribute("Name);
就可以了
⑷ java怎麼把變數放到緩存中
java變數放到緩存中的機制如下:
Java中有中間緩存變數來儲存其單個表達式的值,而j的自增自減的結果依然保留在原來的變數儲存區。因為本體是j的值,而單個表達式的值是中間產生的一個臨時變數值,是在整條計算表達式結束後就可以拋棄的值,所以用個臨時中間緩存變數在放就可以了。這就可以實現自增自減運算在計算時值的加減1順序差異產生的表達式與本體值差異的兩個變數儲存。
如下代碼:
packagecom.qiu.lin.he;
publicclassCeShi{
publicstaticvoidmain(String[]args){
for(inti=0;i<10;i++){
for(intj=0;j<10;j++){
inttemp=i;//中間變數,進行緩存
i=j;
j=temp;
System.out.println(i+"和j的值為"+j);
}
}
}
}
結果如下:
⑸ java修改 方法 緩存沒
緩存是在web開發中經常用到的,將程序經常使用到或調用到的對象存在內存中,或者是耗時較長但又不具有實時性的查詢數據放入內存中,在一定程度上可以提高性能和效率。下面我實現了一個簡單的緩存,步驟如下。
創建緩存對象EntityCache.java
?
04142
public class EntityCache { /** * 保存的數據 */ private Object datas; /** * 設置數據失效時間,為0表示永不失效 */ private long timeOut; /** * 最後刷新時間 */ private long lastRefeshTime; public EntityCache(Object datas, long timeOut, long lastRefeshTime) { this.datas = datas; this.timeOut = timeOut; this.lastRefeshTime = lastRefeshTime; } public Object getDatas() { return datas; } public void setDatas(Object datas) { this.datas = datas; } public long getTimeOut() { return timeOut; } public void setTimeOut(long timeOut) { this.timeOut = timeOut; } public long getLastRefeshTime() { return lastRefeshTime; } public void setLastRefeshTime(long lastRefeshTime) { this.lastRefeshTime = lastRefeshTime; } }
定義緩存操作介面,ICacheManager.java
?public interface ICacheManager { /** * 存入緩存 * @param key * @param cache */ void putCache(String key, EntityCache cache); /** * 存入緩存 * @param key * @param cache */ void putCache(String key, Object datas, long timeOut); /** * 獲取對應緩存 * @param key * @return */ EntityCache getCacheByKey(String key); /** * 獲取對應緩存 * @param key * @return */ Object getCacheDataByKey(String key); /** * 獲取所有緩存 * @param key * @return */ Map<String, EntityCache> getCacheAll(); /** * 判斷是否在緩存中 * @param key * @return */ boolean isContains(String key); /** * 清除所有緩存 */ void clearAll(); /** * 清除對應緩存 * @param key */ void clearByKey(String key); /** * 緩存是否超時失效 * @param key * @return */ boolean isTimeOut(String key); /** * 獲取所有key * @return */ Set<String> getAllKeys();}
實現介面ICacheManager,CacheManagerImpl.java
這里我使用了ConcurrentHashMap來保存緩存,本來以為這樣就是線程安全的,其實不然,在後面的測試中會發現它並不是線程安全的。
?
686970717273747107
public class CacheManagerImpl implements ICacheManager { private static Map<String, EntityCache> caches = new ConcurrentHashMap<String, EntityCache>(); /** * 存入緩存 * @param key * @param cache */ public void putCache(String key, EntityCache cache) { caches.put(key, cache); } /** * 存入緩存 * @param key * @param cache */ public void putCache(String key, Object datas, long timeOut) { timeOut = timeOut > 0 ? timeOut : 0L; putCache(key, new EntityCache(datas, timeOut, System.currentTimeMillis())); } /** * 獲取對應緩存 * @param key * @return */ public EntityCache getCacheByKey(String key) { if (this.isContains(key)) { return caches.get(key); } return null; } /** * 獲取對應緩存 * @param key * @return */ public Object getCacheDataByKey(String key) { if (this.isContains(key)) { return caches.get(key).getDatas(); } return null; } /** * 獲取所有緩存 * @param key * @return */ public Map<String, EntityCache> getCacheAll() { return caches; } /** * 判斷是否在緩存中 * @param key * @return */ public boolean isContains(String key) { return caches.containsKey(key); } /** * 清除所有緩存 */ public void clearAll() { caches.clear(); } /** * 清除對應緩存 * @param key */ public void clearByKey(String key) { if (this.isContains(key)) { caches.remove(key); } } /** * 緩存是否超時失效 * @param key * @return */ public boolean isTimeOut(String key) { if (!caches.containsKey(key)) { return true; } EntityCache cache = caches.get(key); long timeOut = cache.getTimeOut(); long lastRefreshTime = cache.getLastRefeshTime(); if (timeOut == 0 || System.currentTimeMillis() - lastRefreshTime >= timeOut) { return true; } return false; } /** * 獲取所有key * @return */ public Set<String> getAllKeys() { return caches.keySet(); }}
CacheListener.java,監聽失效數據並移除。
?public class CacheListener{ Logger logger = Logger.getLogger("cacheLog"); private CacheManagerImpl cacheManagerImpl; public CacheListener(CacheManagerImpl cacheManagerImpl) { this.cacheManagerImpl = cacheManagerImpl; } public void startListen() { new Thread(){ public void run() { while (true) { for(String key : cacheManagerImpl.getAllKeys()) { if (cacheManagerImpl.isTimeOut(key)) { cacheManagerImpl.clearByKey(key); logger.info(key + "緩存被清除"); } } } } }.start(); }}
測試類TestCache.java
?public class TestCache { Logger logger = Logger.getLogger("cacheLog"); /** * 測試緩存和緩存失效 */ @Test public void testCacheManager() { CacheManagerImpl cacheManagerImpl = new CacheManagerImpl(); cacheManagerImpl.putCache("test", "test", 10 * 1000L); cacheManagerImpl.putCache("myTest", "myTest", 15 * 1000L); CacheListener cacheListener = new CacheListener(cacheManagerImpl); cacheListener.startListen(); logger.info("test:" + cacheManagerImpl.getCacheByKey("test").getDatas()); logger.info("myTest:" + cacheManagerImpl.getCacheByKey("myTest").getDatas()); try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("test:" + cacheManagerImpl.getCacheByKey("test")); logger.info("myTest:" + cacheManagerImpl.getCacheByKey("myTest")); } /** * 測試線程安全 */ @Test public void testThredSafe() { final String key = "thread"; final CacheManagerImpl cacheManagerImpl = new CacheManagerImpl(); ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { exec.execute(new Runnable() { public void run() { if (!cacheManagerImpl.isContains(key)) { cacheManagerImpl.putCache(key, 1, 0); } else { //因為+1和賦值操作不是原子性的,所以把它用synchronize塊包起來 synchronized (cacheManagerImpl) { int value = (Integer) cacheManagerImpl.getCacheDataByKey(key) + 1; cacheManagerImpl.putCache(key,value , 0); } } } }); } exec.shutdown(); try { exec.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e1) { e1.printStackTrace(); } logger.info(cacheManagerImpl.getCacheDataByKey(key).toString()); }}
testCacheManager()輸出結果如下:
?
123456789101112
2017-4-17 10:33:51 io.github.brightloong.cache.TestCache testCacheManager信息: test:test2017-4-17 10:33:51 io.github.brightloong.cache.TestCache testCacheManager信息: myTest:myTest2017-4-17 10:34:01 io.github.brightloong.cache.CacheListener$1 run信息: test緩存被清除2017-4-17 10:34:06 io.github.brightloong.cache.CacheListener$1 run信息: myTest緩存被清除2017-4-17 10:34:11 io.github.brightloong.cache.TestCache testCacheManager信息: test:null2017-4-17 10:34:11 io.github.brightloong.cache.TestCache testCacheManager信息: myTest:null
testThredSafe()輸出結果如下(選出了各種結果中的一個舉例):
?
12
2017-4-17 10:35:36 io.github.brightloong.cache.TestCache testThredSafe信息: 96
可以看到並不是預期的結果100,為什麼呢?ConcurrentHashMap只能保證單次操作的原子性,但是當復合使用的時候,沒辦法保證復合操作的原子性,以下代碼:
?
123
if (!cacheManagerImpl.isContains(key)) { cacheManagerImpl.putCache(key, 1, 0); }
多線程的時候回重復更新value,設置為1,所以出現結果不是預期的100。所以辦法就是在CacheManagerImpl.java中都加上synchronized,但是這樣一來相當於操作都是串列,使用ConcurrentHashMap也沒有什麼意義,不過只是簡單的緩存還是可以的。或者對測試方法中的run裡面加上synchronized塊也行,都是大同小異。
⑹ java內存或者是緩存管理怎麼實現
我不太清楚你為什麼用map來存放數據?你用什麼作為key呢?如果是我做的話我會自定義一個對象,裡面大體上有如下屬性:發言人、發言時間、發言內容等。然後用list存放這些對象,list是由順序的。如果長度到達一定值可以把最先放進去的對象清除掉或移動到其他地方。
⑺ java關於緩存操作的問題
話沒說清楚吧。
list操作 一般是如有有人新增了一條記錄到資料庫,然後當你刷新緩存的時候,他會將目前的這條記錄 新增到緩存中list的集合裡面。碰到這種aba的話你要麼加鎖、同步,或者二次讀取緩存。
⑻ java 怎麼設置只對js css 開啟瀏覽器緩存
function cache_none($interval = 60)
{
// 向後兼容HTTP/1.0
header("Expires: 0");
header("Pragma: no-cache");
// 支持HTTP/1.1
header("Cache-Control: no-cache,no-store,max-age=0,s-maxage=0,must-revalidate");
}
當調用session_start()時,PHP會自動發送一個no-cache類的頭來阻止緩存數據,
要注意的是:
通過POST方法發送的請求不能以如上所述的方式緩存。
⑼ java 中如何進行頁面緩存
可以在要執行的頁面中通過set方法設置要緩存的內容,之後通過get方式獲取到設置的內容
舉例:
第一個訪問頁面:
request.setAttribute("username",zhangsan");
第二個跳轉頁面:
Srting username = request.getAttribute(''username'');
此時即可獲取到username的存儲信息。
⑽ 使用java實現以個簡單的緩存機制
你這個分數太少了吧,程序到是有,不過給你有點可惜
CacheMgr.java
import java.util.*;
import cn.javass.framework.cache.vo.CacheConfModel;
public class CacheMgr {
private static Map cacheMap = new HashMap();
private static Map cacheConfMap = new HashMap();
private CacheMgr(){
}
private static CacheMgr cm = null;
public static CacheMgr getInstance(){
if(cm==null){
cm = new CacheMgr();
Thread t = new ClearCache();
t.start();
}
return cm;
}
/**
* 增加緩存
* @param key
* @param value
* @param ccm 緩存對象
* @return
*/
public boolean addCache(Object key,Object value,CacheConfModel ccm){
boolean flag = false;
cacheMap.put(key, value);
cacheConfMap.put(key, ccm);
System.out.println("now addcache=="+cacheMap.size());
return true;
}
/**
* 刪除緩存
* @param key
* @return
*/
public boolean removeCache(Object key){
cacheMap.remove(key);
cacheConfMap.remove(key);
System.out.println("now removeCache=="+cacheMap.size());
return true;
}
/**
* 清除緩存的類
* @author wanglj
* 繼承Thread線程類
*/
private static class ClearCache extends Thread{
public void run(){
while(true){
Set tempSet = new HashSet();
Set set = cacheConfMap.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
Object key = it.next();
CacheConfModel ccm = (CacheConfModel)cacheConfMap.get(key);
//比較是否需要清除
if(!ccm.isForever()){
if((new Date().getTime()-ccm.getBeginTime())>= ccm.getDurableTime()*60*1000){
//可以清除,先記錄下來
tempSet.add(key);
}
}
}
//真正清除
Iterator tempIt = tempSet.iterator();
while(tempIt.hasNext()){
Object key = tempIt.next();
cacheMap.remove(key);
cacheConfMap.remove(key);
}
System.out.println("now thread================>"+cacheMap.size());
//休息
try {
Thread.sleep(60*1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
CacheConfModel.java
public class CacheConfModel implements java.io.Serializable{
private long beginTime;
private boolean isForever = false;
private int rableTime;
public long getBeginTime() {
return beginTime;
}
public void setBeginTime(long beginTime) {
this.beginTime = beginTime;
}
public boolean isForever() {
return isForever;
}
public void setForever(boolean isForever) {
this.isForever = isForever;
}
public int getDurableTime() {
return rableTime;
}
public void setDurableTime(int rableTime) {
this.rableTime = rableTime;
}
}
順便說一句,緩存的管理不是靠時間久來計算的,是靠最大不活動間隔計算的,你的設計思想有問題