Memcached實現簡單業務處理

來源:互聯網
上載者:User

--------memcache 基本業務代碼解讀

1、建立Memcache用戶端串連MemCacheConnection

package com.boonya.mecache.store;import com.danga.MemCached.MemCachedClient;import com.danga.MemCached.SockIOPool;public class MemCacheConnection {  private static final MemCachedClient memCachedClient = new MemCachedClient();  static {  String[] servers = {  // "192.168.20.10:11211"  "127.0.0.1:11211" };  Integer[] weights = { 3, 3 };  /* 執行個體化串連 */  SockIOPool pool = SockIOPool.getInstance();  pool.setServers(servers);  pool.setWeights(weights);  /* 設定5個串連池 最大串連數250個 空閑時間6小時 */  pool.setInitConn(5);  pool.setMinConn(5);  pool.setMaxConn(250);  pool.setMaxIdle(1000 * 60 * 60 * 24);  pool.setMaintSleep(30);  pool.setNagle(false);  pool.setSocketTO(3000);  pool.setSocketConnectTO(0);  pool.initialize();  memCachedClient.setPrimitiveAsString(true);  memCachedClient.setSanitizeKeys(false); } public static MemCachedClient getMemcacheClient() {    return memCachedClient;   }}

2、MemCache快取資料操作MemStoragehandler

package com.boonya.mecache.store;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import com.danga.MemCached.MemCachedClient;public class MemStoragehandler { MemCachedClient memClient = MemCacheConnection.getMemcacheClient(); Connection conn = null; Statement stmt = null; /**  * 執行業務處理操作  *   * @param myItems  *            緩衝集合對象  */ @SuppressWarnings("rawtypes") public void doService(ArrayList myItems) {  boolean isSaved = this.saveItems(myItems);  if (isSaved) {   this.deleteMemcacheItem(myItems, memClient, isSaved);  } } /**  * 刪除MemCache緩衝中資料  *   * @param myItems  * @param memClient  * @param isSaved  */ @SuppressWarnings("rawtypes") private void deleteMemcacheItem(ArrayList myItems,   MemCachedClient memClient, boolean isSaved) {  if (isSaved) {   for (int d = 0; d < myItems.size(); d++) {    memClient.delete((String) myItems.get(d));   }  } } /**  * MemCache緩衝中資料批量入庫  *   * @param myItems  *                    資料集合  * @return true/false 儲存標誌  */ @SuppressWarnings("rawtypes") private boolean saveItems(ArrayList myItems) {  try {   DBConnection dbconn = new DBConnection();   conn = dbconn.getConnectionByJDBC("127.0.0.1", "3306", "lbs",     "root", "root");   stmt = conn.createStatement();   conn.setAutoCommit(false);   /* 從memcached裡遍曆一個一個取值 */   for (int h = 0; h < myItems.size(); h++) {    String str = (String) memClient.get((String) myItems.get(h));    String key = (String) myItems.get(h);    String keyarr[] = key.split("_");    String sql = DBCreateSQL.getkey(str, keyarr[0]);//建立SQL語句    stmt.executeUpdate(sql);   }   conn.commit();  } catch (Exception e) {   System.out.println(e.getMessage());   e.printStackTrace();   /* 如果事務提交失敗flag置為1並復原 */   try {    conn.rollback();   } catch (SQLException e1) {    e1.printStackTrace();   }   ServiceLog.logerr(myItems.size());   return false;  } finally {   this.free(conn, stmt);  }  return true; } /**  * 釋放資料庫連接資源佔用  * @param conn  * @param stmt  */ private void free(Connection conn, Statement stmt) {  try {   if (stmt != null) {    stmt.close();   }   stmt = null;  } catch (Exception e) {   e.printStackTrace();  }  try {   if (conn != null) {    conn.setAutoCommit(true);    conn.close();   }   conn = null;  } catch (Exception e) {   e.printStackTrace();  } }}

3、MemCache快取資料讀取MemDataSearching

package com.boonya.mecache.store;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import com.danga.MemCached.MemCachedClient;public class MemDataSearching { /**  * 遍曆memCached方法,返回key arrayList 在memCached中實際操作為 stats items -> stats  * (此種方式不推薦,遍曆太耗時間,降低了效能 最好事先定義好Object Storage Service在memCache的時候是索引值對形式  * 如:key-name,value=map/hashMap 然後再一層一層的去map中取值,速度會很快 )  */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static ArrayList searchdata() {  MemCachedClient memClient = MemCacheConnection.getMemcacheClient();  ArrayList keys = new ArrayList(30000);  Map slabs = memClient.statsItems();  Iterator itemsItr = slabs.keySet().iterator();  while (itemsItr.hasNext()) {   String serverInfo = itemsItr.next().toString();   Map itemNames = (Map) slabs.get(serverInfo);   Iterator itemNameItr = itemNames.keySet().iterator();   while (itemNameItr.hasNext()) {    String itemName = itemNameItr.next().toString();    String[] itemAtt = itemName.split(":");    if (itemAtt[2].startsWith("number")) {     Map cachedDump = memClient.statsCacheDump(       Integer.parseInt(itemAtt[1]), 0);     Iterator itr = cachedDump.keySet().iterator();     while (itr.hasNext()) {      String serverInfo2 = itr.next().toString();      Map items = (Map) cachedDump.get(serverInfo2);      Iterator keyItr = items.keySet().iterator();      while (keyItr.hasNext()) {       String key = keyItr.next().toString();       String memKey = key;       keys.add(memKey);      }     }    }   }  }  return keys; } /**  * 改進方式讀取,返回對應表對象集合 ( 事先定義好Object Storage Service在memCache的時候是索引值對形式  * 如:key-name,value=map/hashMap 然後再一層一層的去map中取值,速度會很快  * 結構:分區(多個),分表(多個),表資料行(多行)  *   * 也可以使用分區分表的方式 )  * @param tableName  查詢資料表的名稱  *   * @return  */ @SuppressWarnings({ "rawtypes"}) public static List searchdataPlus(String tableName) {  MemCachedClient memClient = MemCacheConnection.getMemcacheClient();  Map tableAreas= memClient.statsItems();            // 擷取MAP表集合  Iterator iteratorTableArea = tableAreas.keySet().iterator();  while(iteratorTableArea.hasNext()) {              //之所以用while而不用if是因為可能會有多個表分區   Map area = (Map) iteratorTableArea.next();    // 擷取MAP表   if (area!= null) {    if (area.containsKey(tableName)) {        // 分區下是否存在需要訪問的表     Map table=(Map) area.get(tableName);     if(table!=null){      return (List) table.values();     //表中的對象集合     }    }   }  }  return null; }} 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.