激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java實現一個簡單的緩存方法

Java實現一個簡單的緩存方法

2020-09-13 12:21BrightLoong Java教程

本篇文章主要介紹了Java實現一個簡單的緩存方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

緩存是在web開發中經常用到的,將程序經常使用到或調用到的對象存在內存中,或者是耗時較長但又不具有實時性的查詢數據放入內存中,在一定程度上可以提高性能和效率。下面我實現了一個簡單的緩存,步驟如下。

創建緩存對象EntityCache.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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來保存緩存,本來以為這樣就是線程安全的,其實不然,在后面的測試中會發現它并不是線程安全的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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,監聽失效數據并移除。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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()輸出結果如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
2017-4-17 10:33:51 io.github.brightloong.cache.TestCache testCacheManager
信息: test:test
2017-4-17 10:33:51 io.github.brightloong.cache.TestCache testCacheManager
信息: myTest:myTest
2017-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:null
2017-4-17 10:34:11 io.github.brightloong.cache.TestCache testCacheManager
信息: myTest:null

testThredSafe()輸出結果如下(選出了各種結果中的一個舉例):

?
1
2
2017-4-17 10:35:36 io.github.brightloong.cache.TestCache testThredSafe
信息: 96

可以看到并不是預期的結果100,為什么呢?ConcurrentHashMap只能保證單次操作的原子性,但是當復合使用的時候,沒辦法保證復合操作的原子性,以下代碼:

?
1
2
3
if (!cacheManagerImpl.isContains(key)) {
              cacheManagerImpl.putCache(key, 1, 0);
            }

多線程的時候回重復更新value,設置為1,所以出現結果不是預期的100。所以辦法就是在CacheManagerImpl.java中都加上synchronized,但是這樣一來相當于操作都是串行,使用ConcurrentHashMap也沒有什么意義,不過只是簡單的緩存還是可以的。或者對測試方法中的run里面加上synchronized塊也行,都是大同小異。更高效的方法我暫時也想不出來,希望大家能多多指教。

原文鏈接:http://www.jianshu.com/p/bd8dc4a8bbc7#

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 久久久久久久久久久久久九 | 久久免费视频7 | 欧美人人干| 欧美wwwwww| 亚洲一区二区三区四区精品 | 亚洲一区在线视频观看 | 精品成人在线观看 | 毛片大全免费 | 精品国产一区二区三区久久久蜜月 | 91在线色| 精品一区二区三区毛片 | 日韩黄色片在线观看 | 久久久久九九九女人毛片 | 爽爽淫人综合网网站 | av成人免费 | 黄免费在线观看 | 午夜精品福利影院 | 91免费无限观看 | 欧美亚洲国产成人综合在线 | 99精彩视频在线观看 | 日本精品黄色 | 欧美一级二级毛片视频 | 国产免费片 | 一本精品999爽爽久久久 | 亚洲性爰 | 一级免费黄色免费片 | 久久精品探花 | 久久国产乱子伦精品 | 久草高清视频 | 亚洲草原天堂 | 亚洲人成网站免费播放 | 黄色免费av网站 | 国产精品麻豆一区二区三区 | 在线观看视频日本 | www国产免费 | 亚洲国产高清视频 | 亚洲影视在线观看 | 91成人免费在线观看 | 亚洲男人天堂 | 国产精品一区二区视频 | 久久亚洲美女视频 |