ibatis基础上添加memcached缓存

来源:互联网 发布:linux 文件保存 编辑:程序博客网 时间:2024/05/16 13:41

  在ibatis源码基础上修改,增加对memcached支持,通过配置IBatis的xml文件即可实现memcached细粒度话缓存,使用简单,缓存效果好。 spring下首先初始化MemcachedManager对象,或者通过程序初始化也一样,不要用ibatis官方的jar包,否则会冲突

Java代码 复制代码
  1. <bean class="com.ibatis.sqlmap.engine.cache.memcached.memcachedManager" lazy-init="false"  
  2.   
  3.     init-method="init" destroy-method="closePool">  
  4.   
  5.     <property name="serverlist">  
  6.   
  7.         <value>  
  8.   
  9.         192.168.0.1:11111192.168.0.2:11111  
  10.   
  11.         </value>  
  12.   
  13.     </property>  
  14.   
  15.     <property name="initConn" value="5">  
  16.   
  17.     </property>  
  18.   
  19.     <property name="minConn" value="5">  
  20.   
  21.     </property>  
  22.   
  23.     <property name="maxConn" value="200">  
  24.   
  25.     </property>  
  26.   
  27. Unknown end tag for </bean>  



然后配置sqlMapConfig.xml文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"

    "http://ibatis-with-memcached.googlecode.com/files/sql-map-config-2.dtd"> #注意这里,不用官方的,这个dtd文件加了个新属性databaseUrl,区分不同数据库的缓存对象




Java代码 复制代码 收藏代码
  1. <sqlmapconfig>  
  2.   
  3.     <properties resource="cache_config.properties">  
  4.   
  5.     </properties>  
  6.   
  7.     <settings  
  8.   
  9.         cacheModelsEnabled="true" enhancementEnabled="true" lazyLoadingEnabled="true" maxRequests="256" maxSessions="256" maxTransactions="150" useStatementNamespaces="true" databaseUrl="数据库名或地址" #新增加的属性 />  
  10.   
  11. ibatis的xml文件:Albums.xml #创建缓存model  
  12.   
  13. <cachemodel type="MEMCACHED" id="albumsCache">  
  14.   
  15.     <flushinterval hours="12">  
  16.   
  17.     </flushInterval >  
  18.   
  19.     <flushonexecute statement="albums.save">  
  20.   
  21.     </flushOnExecute >  
  22.   
  23.     <flushonexecute statement="albums.update">  
  24.   
  25.     </flushOnExecute >  
  26.   
  27.     <flushonexecute statement="albums.delete">  
  28.   
  29.     </flushOnExecute >  
  30.   
  31.     <property name="pk" value="id">  
  32.   
  33.     </property>  
  34.   
  35.     #可以根据主键进行缓存,可以设置为空,不能不设  
  36.   
  37.     <property name="groupField" value="accId">  
  38.   
  39.     </property>  
  40.   
  41.     #可以根据组(比如用户id)进行缓存,更加细粒度化,可以设置为空,不能不设  
  42.   
  43. Unknown end tag for </cachemodel>  
  44.   
  45. #加入缓存  
  46.   
  47. <select id="findall" parameterClass="albumsObj" resultClass="albumsObj" cacheModel="albumsCache">  
  48.   
  49.     Select ……from albums where accId=1  
  50.   
  51. </select>  
  52.   
  53. <select id="load" parameterClass="albumsObj" resultClass="albumsObj" cacheModel="albumsCache">  
  54.   
  55.     Select ……from albums where id=1  
  56.   
  57. </select>  
  58.   
  59.    
  60.   
  61. #删除对象,删除缓存  
  62.   
  63. <delete id="delete" parameterClass="albumsObj">  
  64.   
  65.     delete from albums where id=1 and accId=1 #(加上accId可以删除分组缓存)  
  66.   
  67. </delete>  

Java代码 复制代码 收藏代码
  1. package com.ibatis.sqlmap.engine.cache.memcached;   
  2.    
  3. import java.io.Serializable;   
  4. import java.util.Collection;   
  5. import java.util.Date;   
  6. import java.util.Map;   
  7.    
  8. import org.apache.log4j.Logger;   
  9.    
  10. import com.danga.MemCached.MemCachedClient;   
  11. import com.danga.MemCached.SockIOPool;   
  12.    
  13.    
  14. public class MemcachedManager {   
  15.    
  16.         private static Logger logger = Logger.getLogger(MemcachedManager.class);   
  17.    
  18.         private static String memcachedDomain = "IBATIS_CACHED"// memcached 域名   
  19.    
  20.         private String serverlist;   
  21.    
  22.         private static MemCachedClient mcc = null;   
  23.    
  24.         private SockIOPool pool = null;   
  25.    
  26.         private int initConn = 5;   
  27.    
  28.         private int minConn = 5;   
  29.    
  30.         private int maxConn = 50;   
  31.    
  32.            
  33.         public void init() {   
  34.                 if (mcc != null)   
  35.                         return;   
  36.    
  37.                 logger.info("Initializing ibatis memcached start.");   
  38.                 if (pool == null) {   
  39.                         try {   
  40.                                 pool = SockIOPool.getInstance(memcachedDomain);   
  41.                                 pool.setServers(serverlist.split(","));   
  42.                                 if (!pool.isInitialized()) {   
  43.                                         pool.setInitConn(initConn);   
  44.                                         pool.setMinConn(minConn);   
  45.                                         pool.setMaxConn(maxConn);   
  46.                                         pool.setMaintSleep(30);   
  47.                                         pool.setNagle(false);   
  48.                                         pool.setSocketTO(60 * 60);   
  49.                                         pool.setSocketConnectTO(0);   
  50.                                         pool.initialize();   
  51.                                 }   
  52.                         } catch (Exception ex) {   
  53.                                 logger.error(ex.getMessage());   
  54.                         }   
  55.                 }   
  56.    
  57.                 if (mcc == null) {   
  58.                         mcc = new MemCachedClient(memcachedDomain);   
  59.                         mcc.setCompressEnable(false);   
  60.                         mcc.setCompressThreshold(0);   
  61.                 }   
  62.                 logger.info("Initializing youxigu Memcached ok!");   
  63.         }   
  64.    
  65.            
  66.         public void closePool() {   
  67.                 pool.shutDown();   
  68.                 mcc = null;   
  69.                 pool = null;   
  70.                 logger.info("Ibatis memcached pool closed");   
  71.         }   
  72.    
  73.            
  74.         public static boolean set(Object key, Serializable obj) {   
  75.                 logger.debug("set key:" + getKey(key) + ", value:" + obj);   
  76.                 try {   
  77.                         return mcc.set(getKey(key), obj);   
  78.                 } catch (Exception e) {   
  79.                         logger.error("Pool set error!");   
  80.                         e.printStackTrace();   
  81.                 }   
  82.                 return false;   
  83.         }   
  84.    
  85.            
  86.         public static boolean set(Object key, Serializable obj, long cacheTime) {   
  87.                 try {   
  88.                         return mcc.set(getKey(key), obj, new Date(cacheTime));   
  89.                 } catch (Exception e) {   
  90.                         logger.error("Pool set error!");   
  91.                         e.printStackTrace();   
  92.                 }   
  93.                 return false;   
  94.         }   
  95.    
  96.            
  97.         public static void replace(int key, Serializable value, long cacheTime) {   
  98.                 try {   
  99.                         mcc.replace(getKey(key), value, new Date(cacheTime));   
  100.                 } catch (Exception e) {   
  101.                         logger.error(" pool set error!");   
  102.                 }   
  103.         }   
  104.    
  105.            
  106.         public static Object get(Object key) {   
  107.                 Object result = null;   
  108.                 String realkey = getKey(key);   
  109.                 try {   
  110.                         result = mcc.get(realkey);   
  111.                 } catch (Exception e) {   
  112.                         e.printStackTrace();   
  113.                 }   
  114.                 logger.debug("get key:" + getKey(key) + ", value:" + result);   
  115.                 return result;   
  116.         }   
  117.    
  118.            
  119.         public static void setCounter(Object key, long count) {   
  120.                 try {   
  121.                         mcc.storeCounter(getCountKey(key), count);   
  122.                 } catch (Exception e) {   
  123.                         logger.error("Pool setCounter error!");   
  124.                 }   
  125.         }   
  126.    
  127.            
  128.         public static void addCounter(Object key) {   
  129.                 if(mcc.get(getCountKey(key))==null){   
  130.                         mcc.storeCounter(getCountKey(key), 0);   
  131.                 }   
  132.                 try {   
  133.                         mcc.incr(getCountKey(key));   
  134.                 } catch (Exception e) {   
  135.                         logger.error("Pool setCounter error!");   
  136.                 }   
  137.         }   
  138.    
  139.            
  140.         public static void decreaseCounter(Object key) {   
  141.                 try {   
  142.                         mcc.decr(getCountKey(key));   
  143.                 } catch (Exception e) {   
  144.                         logger.error("Pool setCounter error!");   
  145.                 }   
  146.         }   
  147.    
  148.            
  149.         public static void addCounter(Object key, long addValue) {   
  150.                 try {   
  151.                         mcc.incr(getCountKey(key), addValue);   
  152.                 } catch (Exception e) {   
  153.                         logger.error(" pool setCounter error!");   
  154.                 }   
  155.         }   
  156.    
  157.            
  158.         public static long getCounter(Object key) {   
  159.                 long result = 0;   
  160.                 try {   
  161.                         result = mcc.getCounter(getCountKey(key));   
  162.                 } catch (Exception e) {   
  163.                         logger.error(e.getMessage());   
  164.                 }   
  165.                 return result;   
  166.         }   
  167.    
  168.            
  169.         public static boolean delete(Object key) {   
  170.                 try {   
  171.                         return mcc.delete(getKey(key));   
  172.                 } catch (Exception e) {   
  173.                         logger.error(e.getMessage());   
  174.                 }   
  175.                 return false;   
  176.         }   
  177.    
  178.            
  179.         public static long deleteCounter(Object key) {   
  180.                 try {   
  181.                         return mcc.decr(getCountKey(key));   
  182.                 } catch (Exception e) {   
  183.                         logger.error(" pool setCounter error!");   
  184.                 }   
  185.                 return 0;    
  186.         }   
  187.    
  188.            
  189.         public static void flushAll() {   
  190.                 mcc.flushAll();   
  191.         }   
  192.            
  193.         @SuppressWarnings("unchecked")   
  194.         public static long size(){   
  195.                 long size=0L;   
  196.                 Map<String,Map<String,String>> status=mcc.statsItems();   
  197.                 Collection<Map<String,String>> values=status.values();   
  198.                 for (Map<String,String> state:values) {   
  199.                         String num=state.get("items:1:number");   
  200.                         if(num==null)   
  201.                                 continue;   
  202.                            
  203.                         size+=Long.parseLong(state.get("items:1:number"));   
  204.                 }   
  205.                 return size;   
  206.         }   
  207.    
  208.            
  209.         private static String getKey(Object key) {   
  210.                 return memcachedDomain + "@" + key;   
  211.         }   
  212.    
  213.         private static String getCountKey(Object key) {   
  214.                 return memcachedDomain + "@" + key + "_count";   
  215.         }   
  216.    
  217.            
  218.         public void setServerlist(String serverlist) {   
  219.                 this.serverlist = serverlist;   
  220.         }   
  221.    
  222.            
  223.         public void setInitConn(int initConn) {   
  224.                 this.initConn = initConn;   
  225.         }   
  226.    
  227.            
  228.         public void setMinConn(int minConn) {   
  229.                 this.minConn = minConn;   
  230.         }   
  231.    
  232.            
  233.         public void setMaxConn(int maxConn) {   
  234.                 this.maxConn = maxConn;   
  235.         }   
  236.    
  237.            
  238.         public void setMemcachedDomain(String memcachedKey) {   
  239.                 MemcachedManager.memcachedDomain = memcachedKey;   
  240.         }   
  241. }   
原创粉丝点击