当前位置:首页 » 文件管理 » java设置缓存

java设置缓存

发布时间: 2022-09-27 07:00:47

⑴ 如何用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;
}
}
顺便说一句,缓存的管理不是靠时间久来计算的,是靠最大不活动间隔计算的,你的设计思想有问题

热点内容
android图片xml 发布:2024-10-09 11:11:08 浏览:531
交换机基本配置与远程登录怎么做 发布:2024-10-09 11:02:06 浏览:674
服务器远程地址怎么看 发布:2024-10-09 10:43:24 浏览:140
隐身访问访客会增加吗 发布:2024-10-09 10:38:29 浏览:209
vb代码如何编译 发布:2024-10-09 10:22:59 浏览:914
sql无效的连接 发布:2024-10-09 10:19:31 浏览:70
javaif条件 发布:2024-10-09 10:01:04 浏览:958
安卓爱思助手怎么改战区 发布:2024-10-09 09:25:29 浏览:181
安卓手机用什么软件传软件到苹果 发布:2024-10-09 09:11:02 浏览:371
苹果安卓怎么传抖音 发布:2024-10-09 09:10:18 浏览:824