簡介
目前常用的Java用戶端有3種。
MemcachedClient
spymemcached
xmemcached
MemcachedClient:其中筆者親測,在高並發的時候,容易報異常,Out Of Memory。
spy:的效能比xmemcached略差。
xmemcached:雖然是國產,但是首選,效能和穩定性超強。
xmemcached
代碼解析
設定串連池和權重
Java代碼
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("10.11.155.26:11211 10.11.155.41:11211 10.10.76.31:11211 10.10.76.35:11211"), new int[] { 1, 1, 1, 1 }); // 設定串連池大小,即用戶端個數 builder.setConnectionPoolSize(50);
命名空間
Java代碼
memcachedClient.beginWithNamespace("sx"); //命名空間
設定一致性雜湊演算法和FailureMode
Java代碼
try { MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddressMap("10.10.160.153:11211,10.10.160.153:11212")); builder.setSessionLocator(new KetamaMemcachedSessionLocator()); builder.setFailureMode(true); // 在此模式下,某個節點掛掉的情況下,往這個節點的請求都將直接拋出MemcachedException的異常。 MemcachedClient client = builder.build(); } catch (Exception e) { System.out.println("自訂異常"); e.printStackTrace(); }
添加狀態監聽器
Java代碼
memcachedClient.addStateListener(new MemcachedClientStateListener());//此處用的是一個匿名類
與spring3.2.5的整合
Xml代碼
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <!-- 設定檔 --> <bean id="configproperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:application.properties</value> </list> </property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configproperties" /> </bean> <!-- memcached初始化 --> <bean id="builder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder"> <constructor-arg> <bean class="net.rubyeye.xmemcached.utils.AddrUtil" factory-method="getAddresses"> <constructor-arg value="${memcached.host}" /> </bean> </constructor-arg> </bean> <bean id="memcachedClient" class="net.rubyeye.xmemcached.MemcachedClient" factory-bean="builder" factory-method="build" destroy-method="shutdown" /> </beans>
出自iteye,作者:85977328
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/tools/