構建高效能服務(一)ConcurrentSkipListMap和連結串列構建高效能Java Memcached
1、對常用功能建立快取模組
2、網頁儘量靜態化
3、使用單獨的圖片伺服器,降低伺服器壓力,使其不會因為圖片載入造成崩潰
4、使用映象解決不同網路接入商和不同地域使用者訪問差異
5、資料庫叢集圖表雜湊
6、加強網路層硬體配置,硬的不行來軟的。
7、終極辦法:負載均衡
場景
快取伺服器是網際網路後端服務中常用的基礎設施。
場景(一)圖片伺服器上儲存了大量圖片,為了提高圖片服務的吞吐量,希望把熱門的圖片載入到記憶體中。
場景(二)分散式儲存服務,為提高訪問吞吐,把大量的meta資訊儲存在記憶體中。
問題
但是使用Java語言開發快取服務,不可避免的遇到GC問題。無論使用ehcache是基於Map實現的快取,都會產生大量Minor GC無法回收的物件,最終導致CMS或Full GC,對系統吞吐造成影響。通過觀察這類服務產生的GC日誌,可以觀察到頻繁的CMS。這裡簡單介紹下CMS的過程即對系統的影響,CMS兩階段標記,減少stop the world的時間,如圖紅色部分為STW(stop the world)。
CMS日誌如下:
9.780: [GC [1 CMS-initial-mark: 507883K(507904K)] 521962K(521984K), 0.0029230 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
Total time for which application threads were stopped: 0.0029970 seconds
CMS第一次標記,stop the world。以下各個步驟則不影響Java Threads工作,即併發模式。
9.783: [CMS-concurrent-mark-start]
9.913: [CMS-concurrent-mark: 0.130/0.130 secs] [Times: user=0.26 sys=0.00, real=0.13 secs]
9.913: [CMS-concurrent-preclean-start]
9.914: [CMS-concurrent-preclean: 0.001/0.001 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
9.914: [CMS-concurrent-abortable-preclean-start]
9.914: [CMS-concurrent-abortable-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
Application time: 0.1317920 seconds
9.914: [GC[YG occupancy: 14079 K (14080 K)]9.914: [Rescan (parallel) , 0.0023580 secs]9.917: [weak refs processing, 0.0000060 secs]
[1 CMS-remark: 507883K(507904K)] 521962K(521984K), 0.0024100 secs] [Times: user=0.01 sys=0.00, real=0.00 secs]
Total time for which application threads were stopped: 0.0025420 seconds
Rescan為第二次標記,STW。
解決方案
構造和Memcached slab/chunk類似的Java記憶體管理方式。為快取的物件分配一組chunck,相同Size的Chunk合成一組Slab。初始slab設為100B,如果快取物件小於100B,放入100B slab,如果大於100B,小於 100B * Growth Factor = 1.27 = 127B,則放入127B slab。因此需要一個快速排序的資料結構來實現slab。我用ConcurrentSkipListMap實現slab,查詢插入時間複雜度和二叉樹一致,但實現更簡單。程式碼如下,
Java程式碼- public boolean put(K key, byte[] value) {
- Map.Entry<Float, LocalMCSlab> entry = null;
- Float theSize = Float.valueOf(value.length);
- Stat.set("CacheSize=", ((getCurrentTotalCacheSize() / 1024f)) + "KB");
- // 以cache size為key,以chunks map為value,如果比這個cache size大得slab不存在,則建立一個
- // 否則,在大約cache size的slab中找一個最小的slab
- if((entry = slabs.tailMap(theSize).firstEntry()) == null) {
- Float floorKey = slabs.floorKey(theSize);
- float needSize = floorKey == null ? theSize : floorKey * scale;
- while(needSize < theSize) {
- needSize = needSize * scale;
- }
- LocalMCSlab<K, byte[]> slab = new LocalMCSlab<K, byte[]>((int) needSize);
- slab.put(key, value, false);
- slabs.put(needSize, slab);
- return true;
- }
- else {
- // 噹噹前全部cache size + 這個快取的size > 分配給整個cache的initSize時,則需使用LRU策略
- boolean isLRU = getCurrentTotalCacheSize() + theSize > initSize;
- entry.getValue().put(key, value, isLRU);
- return true;
- }
- }
每一個slab基於一個Map<K, V>實現。同時為實現LRU,實現了一個連結串列從頭插入從尾部取出,這樣連結串列尾部物件為last recent used,程式碼如下,
Java程式碼- private static class LinkedListNode {
- public LinkedListNode previous;
- public LinkedListNode next;
- public Object object;
- /**
- * Constructs a new linked list node.
- * @param object the Object that the node represents.
- * @param next a reference to the next LinkedListNode in the list.
- * @param previous a reference to the previous LinkedListNode in the list.
- */
- public LinkedListNode(Object object, LinkedListNode next,
- LinkedListNode previous) {
- this.object = object;
- this.next = next;
- this.previous = previous;
- }
- ...
- }
- public static class LinkedList {
- /**
- * The root of the list keeps a reference to both the first and last
- * elements of the list.
- */
- private LinkedListNode head = new LinkedListNode("head", null, null);
- /**
- * Creates a new linked list.
- */
- public LinkedList() {
- head.next = head.previous = head;
- }
- /**
- * Returns the first linked list node in the list.
- *
- * @return the first element of the list.
- */
- public LinkedListNode getFirst() {
- LinkedListNode node = head.next;
- if (node == head) {
- return null;
- }
- return node;
- }
- /**
- * Returns the last linked list node in the list.
- *
- * @return the last element of the list.
- */
- public LinkedListNode getLast() {
- LinkedListNode node = head.previous;
- if (node == head) {
- return null;
- }
- return node;
- }
- public LinkedListNode removeLast() {
- LinkedListNode node = head.previous;
- if (node == head) {
- return null;
- }
- head.previous = node.previous;
- return node;
- }
- /**
- * Adds a node to the beginning of the list.
- *
- * @param node the node to add to the beginning of the list.
- */
- public LinkedListNode addFirst(LinkedListNode node) {
- node.next = head.next;
- head.next = node;
- node.previous = head;
- node.next.previous = node;
- return node;
- }
- ...
- }
當LRU策略發生時,不再建立新的byte[],而是重寫最老的一個byte[],並把這個cache移動到連結串列頭部
Java程式碼- if(removeLRU) {
- LinkedListNode lastNode = ageList.removeLast();
- Object lasthashKey = hashKeyMap.remove(lastNode.object);
- if(lasthashKey == null) {
- return false;
- }
- Stat.inc("eviction[" + this.chunkSize + "]");
- CacheObject<byte[]> data = map.get(lasthashKey);
- System.arraycopy(value, 0, data.object, 0, value.length);
- data.length = value.length;
- // update key / hashkey mapping
- hashKeyMap.put(key, lasthashKey);
- lastNode.object = key;
- ageList.addFirst(lastNode);
- }
注意使用了一個hashKeyMap,它的key是這次put的cache物件的key,value作為byte[]的key,在第一次建立byte[]時建立。這樣做也是為了不重新建立物件。
全部程式碼及測試類見附件。
測試
測試引數
java -Xms2g -Xmx2g -Xmn128m -XX:+UseConcMarkSweepGC -server -XX:SurvivorRatio=5 -XX:CMSInitiatingOccupancyFraction=80 -XX:+PrintTenuringDistribution -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -Xloggc:./gc.log test.TestMain
測試表現穩定,記憶體全部在Minor GC階段回收。
分配cache=1G,實際CacheSize==1048625.2KB;
各個slab chunk個數:
Chunk[100.0] count==5
Chunk[209758.16] count==1231
Chunk[165163.9] count==4938
總結
本來想寫一個虛擬碼的,後來覺得Java中還是有不少比較好的資料結構,比如ConcurrentSkipListMap和LRUMap還是想介紹給大家。因此就寫了這個比較粗糙的版本,基本可以反映出類似Memcached slab/chunk管理記憶體的方式。實際測試中表現也有一定收益。可以基於這個版本開發線上服務。但是這個實現裡面還沒有很好的處理併發問題,對記憶體的使用也有一些坑。使用中如果遇到問題,歡迎大家一起討論。
原文:http://maoyidao.iteye.com/blog/1559420