「java缓存代码」内存缓存java

博主:adminadmin 2022-11-28 05:24:05 54

本篇文章给大家谈谈java缓存代码,以及内存缓存java对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java中文件读取的缓存问题

read方法又不止一个……

public int read(byte[] b)

throws IOException

从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b

中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾或者抛出异常前,此方法一直阻塞。

如果 b 的长度为 0,则不读取任何字节并返回

0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值

-1;否则,至少读取一个字节并将其存储在 b 中。

java修改 方法 缓存没

缓存是在web开发中经常用到的,将程序经常使用到或调用到的对象存在内存中,或者是耗时较长但又不具有实时性的查询数据放入内存中,在一定程度上可以提高性能和效率。下面我实现了一个简单的缓存,步骤如下。

创建缓存对象EntityCache.java

?

123456789101112131415161718192021222324252627282930313233343536373839404142

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

?

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667

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 */ MapString, 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 */ SetString getAllKeys();}

实现接口ICacheManager,CacheManagerImpl.java

这里我使用了ConcurrentHashMap来保存缓存,本来以为这样就是线程安全的,其实不然,在后面的测试中会发现它并不是线程安全的。

?

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107

public class CacheManagerImpl implements ICacheManager { private static MapString, EntityCache caches = new ConcurrentHashMapString, 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 MapString, 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 SetString getAllKeys() { return caches.keySet(); }}

CacheListener.java,监听失效数据并移除。

?

1234567891011121314151617181920212223

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

?

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556

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如何将页面每次请求获得的数据缓存起来供使用?

?阏飧龊诵牡牡胤剑?褪莂ction这儿不去查数据库,而拿到缓存的数据再直接返回到前台嘛。核心代码逻辑就是:longobsoleteTime=1天;

List

list=cache.get(abc,

obsoleteTime);if(list==null){

list=manager.search(..);

这样的缓存策略很多的啊。比如oscache就可以达到要求,而且用起来很简单,只要一个jar,自己抽象一个cache的接口,套上去,就能用了。

JAVA几种缓存技术介绍说明

1、OSCache

OSCache是个一个广泛采用的高性能的J2EE缓存框架,OSCache能用于任何java应用程序的普通的缓存解决方案。

OSCache有以下特点:

(1)缓存任何对象,你可以不受限制的缓存部分jsp页面或HTTP请求,任何java对象都可以缓存。

永久缓存--缓存能随意的写入硬盘,因此答应昂贵的创建(eXPensive-to-create)数据来保持缓存,甚至能让应用重启。

(2)支持集群--集群缓存数据能被单个的进行参数配置,不需要修改代码。

缓存记录的过期--你可以有最大限度的控制缓存对象的过期,包括可插入式的刷新策略(假如默认性能不需要时)。

2、Java Caching System

JSC(Java Caching System)是一个用分布式的缓存系统,是基于服务器的java应用程序。它是通过提供治理各种动态缓存数据来加速动态web应用。

JCS和其他缓存系统一样,也是一个用于高速读取,低速写入的应用程序。

动态内容和报表系统能够获得更好的性能。

假如一个网站,有重复的网站结构,使用间歇性更新方式的数据库(而不是连续不断的更新数据库),被重复搜索出相同结果的,就能够通过执行缓存方式改进其性能和伸缩性。

3、EHCache

EHCache 是一个纯java的在进程中的缓存,它具有以下特性:快速,简单,为Hibernate2.1充当可插入的缓存,最小的依靠性,全面的文档和测试。

4、JCache

JCache是个开源程序,正在努力成为JSR-107开源规范,JSR-107规范已经很多年没改变了。这个版本仍然是构建在最初的功能定义上。

5、ShiftOne

ShiftOne Java Object Cache是一个执行一系列严格的对象缓存策略的Java lib,就像一个轻量级的配置缓存工作状态的框架。

6、SwarmCache

SwarmCache是一个简单且有效的分布式缓存,它使用ip multicast与同一个局域网的其他主机进

行通讯,是非凡为集群和数据驱动web应用程序而设计的。

SwarmCache能够让典型的读操作大大超过写操作的这类应用提供更好的性能支持。

SwarmCache使用JavaGroups来治理从属关系和分布式缓存的通讯。

扩展资料

Java中缓存存在的原因:

一 般情况下,一个网站,或者一个应用,它的一般形式是,浏览器请求应用服务器,应用服务器做一堆计算后再请求数据库,数据库收到请求后再作一堆计算后把数据 返回给应用服务器。

应用服务器再作一堆计算后把数据返回给浏览器,这个是一个标准流程。但是随着互连网的普及,上网的人越来越多,网上的信息量也越来越多。

数据库每秒中接受请求的次数也是有限的,如果利用有限的资源来提供尽可能大的吞吐量呢。一个办法:减少计算量,缩短请求流程(减少网络io或者硬盘io),这时候缓存就可以大展手脚了。

缓存的基本原理就是打破上图中所描绘的标准流程,在这个标准流程中,任何 一个环节都可以被切断.请求可以从缓存里取到数据直接返回。

关于java缓存代码和内存缓存java的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-28,除非注明,否则均为首码项目网原创文章,转载请注明出处。