当前位置:学者斋 >

计算机 >java语言 >

Java如何实现一个简单的缓存

Java如何实现一个简单的缓存

缓存是在web开发中经常用到的,将程序经常使用到或调用到的对象存在内存中,或者是耗时较长但又不具有实时性的查询数据放入内存中,在一定程度上可以提高性能和效率。那么,用Java如何实现一个简单的缓存?下面本站小编带大家一起来看看详细内容,希望对大家有所帮助!想了解更多相关信息请持续关注我们应届毕业生考试网!

Java如何实现一个简单的缓存

  创建缓存对象

public class EntityCache {

/**

* 保存的数据

*/

private Object datas;

/**

* 设置数据失效时间,为0表示永不失效

*/

private long timeOut;

/**

* 最后刷新时间

*/

private long lastRefeshTime;

public EntityCache(Object datas, long timeOut, long lastRefeshTime) {

s = datas;

Out = timeOut;

RefeshTime = lastRefeshTime;

}

public Object getDatas() {

return datas;

}

public void setDatas(Object datas) {

s = datas;

}

public long getTimeOut() {

return timeOut;

}

public void setTimeOut(long timeOut) {

Out = timeOut;

}

public long getLastRefeshTime() {

return lastRefeshTime;

}

public void setLastRefeshTime(long lastRefeshTime) {

RefeshTime = lastRefeshTime;

}

}

  定义缓存操作接口,

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,

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

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) {

(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, entTimeMillis()));

}

/**

* 获取对应缓存

* @param key

* @return

*/

public EntityCache getCacheByKey(String key) {

if (ntains(key)) {

return (key);

}

return null;

}

/**

* 获取对应缓存

* @param key

* @return

*/

public Object getCacheDataByKey(String key) {

if (ntains(key)) {

return (key)atas();

}

return null;

}

/**

* 获取所有缓存

* @param key

* @return

*/

public Map<String, EntityCache> getCacheAll() {

return caches;

}

/**

* 判断是否在缓存中

* @param key

* @return

*/

public boolean isContains(String key) {

return ainsKey(key);

}

/**

* 清除所有缓存

*/

public void clearAll() {

r();

}

/**

* 清除对应缓存

* @param key

*/

public void clearByKey(String key) {

if (ntains(key)) {

ve(key);

}

}

/**

* 缓存是否超时失效

* @param key

* @return

*/

public boolean isTimeOut(String key) {

if (!ainsKey(key)) {

return true;

}

EntityCache cache = (key);

long timeOut = imeOut();

long lastRefreshTime = astRefeshTime();

if (timeOut == 0 || entTimeMillis() - lastRefreshTime >= timeOut) {

return true;

}

return false;

}

/**

* 获取所有key

* @return

*/

public Set<String> getAllKeys() {

return et();

}

}

  ,监听失效数据并移除。

public class CacheListener{

Logger logger = ogger("cacheLog");

private CacheManagerImpl cacheManagerImpl;

public CacheListener(CacheManagerImpl cacheManagerImpl) {

eManagerImpl = cacheManagerImpl;

}

public void startListen() {

new Thread(){

public void run() {

while (true) {

for(String key : llKeys()) {

if (meOut(key)) {

rByKey(key);

(key + "缓存被清除");

}

}

}

}

}t();

}

}

  测试类

public class TestCache {

Logger logger = ogger("cacheLog");

/**

* 测试缓存和缓存失效

*/

@Test

public void testCacheManager() {

CacheManagerImpl cacheManagerImpl = new CacheManagerImpl();

ache("test", "test", 10 * 1000L);

ache("myTest", "myTest", 15 * 1000L);

CacheListener cacheListener = new CacheListener(cacheManagerImpl);

tListen();

("test:" + acheByKey("test")atas());

("myTest:" + acheByKey("myTest")atas());

try {

p(20);

} catch (InterruptedException e) {

tStackTrace();

}

("test:" + acheByKey("test"));

("myTest:" + acheByKey("myTest"));

}

/**

* 测试线程安全

*/

@Test

public void testThredSafe() {

final String key = "thread";

final CacheManagerImpl cacheManagerImpl = new CacheManagerImpl();

ExecutorService exec = achedThreadPool();

for (int i = 0; i < 100; i++) {

ute(new Runnable() {

public void run() {

if (!ntains(key)) {

ache(key, 1, 0);

} else {

//因为+1和赋值操作不是原子性的,所以把它用synchronize块包起来

synchronized (cacheManagerImpl) {

int value = (Integer) acheDataByKey(key) + 1;

ache(key,value , 0);

}

}

}

});

}

down();

try {

tTermination(1, );

} catch (InterruptedException e1) {

tStackTrace();

}

(acheDataByKey(key)ring());

}

}

testCacheManager()输出结果如下:

2017-4-17 10:33:51 Cache testCacheManager

信息: test:test

2017-4-17 10:33:51 Cache testCacheManager

信息: myTest:myTest

2017-4-17 10:34:01 eListener$1 run

信息: test缓存被清除

2017-4-17 10:34:06 eListener$1 run

信息: myTest缓存被清除

2017-4-17 10:34:11 Cache testCacheManager

信息: test:null

2017-4-17 10:34:11 Cache testCacheManager

信息: myTest:null

testThredSafe()输出结果如下(选出了各种结果中的一个举例):

2017-4-17 10:35:36 Cache testThredSafe

信息: 96

可以看到并不是预期的结果100,为什么呢?ConcurrentHashMap只能保证单次操作的原子性,但是当复合使用的时候,没办法保证复合操作的'原子性,以下代码:

if (!ntains(key)) {

ache(key, 1, 0);

}

多线程的时候回重复更新value,设置为1,所以出现结果不是预期的100。所以办法就是在中都加上synchronized,但是这样一来相当于操作都是串行,使用ConcurrentHashMap也没有什么意义,不过只是简单的缓存还是可以的。或者对测试方法中的run里面加上synchronized块也行,都是大同小异。更高效的方法我暂时也想不出来,希望大家能多多指教。

标签: JAVA 缓存
  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/31jwj1.html