Java 客戶端連線 Memcached & Spring 整合
阿新 • • 發佈:2019-01-08
Memcached
Java 客戶端連線 Memcached
目前連線 Memcahed 服務的 Java 客戶端主要有以下 3 種方案:- Memcached Client for Java
- SpyMemcahed
- XMemcached
SpyMemcached 的基本使用程式碼
使用 SpyMemcached,需要向專案匯入以下依賴:net.spy:spymemcached以下為 SpyMemcached 的基本操作程式碼,預設 memcahed ip:127.0.0.1:11211
public class MemcachedJavaTest {
private final static Logger log = LogManager.getLogger();
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
// 建立 memcached 客戶端
MemcachedClient client = new MemcachedClient(new InetSocketAddress("127.0.0.1" ,11211));
// 演示各種 memcached 操作
// set 操作
Future fo = client.set("key1",500,"Hello world");
log.debug("set result: " + fo.get());
// get 操作
String key1 = (String) client.get("key1");
log.debug("key1: " + key1);
//del 操作
fo = client.delete("key1" );
log.debug("delete result: " + fo.get());
// add 操作
fo = client.add("key2",500,"Are you OK?");
log.debug("add result: " + fo.get());
// gets, cas 操作
CASValue cas = client.gets("key2"); //獲取 key2 的 cas 令牌
client.cas("key2",cas.getCas(),"Deep Dark Fantatic");
log.debug("key2: " + client.get("key2"));
// append 操作
cas = client.gets("key2");
client.append(cas.getCas(),"key2","!♂ I'm Van ♂");
log.debug("key2: " + client.get("key2"));
// 演示讀寫 Java Bean
User user = new User();
user.setId(123L);
user.setName("assad");
user.setAge(22);
user.setCity("Guangzhou");
// 寫入 Java Bean (寫入Java Bean 的序列化位元組)
client.set(user.getId()+"",500,user);
// 獲取 Java Bean (讀取的時位元組值並反序列化為 Java Bean)
User userGet = (User) client.get(123L+"");
log.debug("user: " + userGet);
// 關閉 memcached 客戶端
client.shutdown();
}
static class User implements Serializable{
private static final long serialVersionUID = 2333L;
private long id ;
private String name;
private int age;
private String city;
//getter,setter,toString
}
}
輸出:16:46:07.585 [main] DEBUG memcached.SpyMemcachedTest - set result: true
16:46:07.591 [main] DEBUG memcached.SpyMemcachedTest - key1: Hello world
16:46:07.593 [main] DEBUG memcached.SpyMemcachedTest - delete result: true
16:46:07.594 [main] DEBUG memcached.SpyMemcachedTest - add result: false
16:46:07.599 [main] DEBUG memcached.SpyMemcachedTest - key2: Deep Dark Fantatic
16:46:07.603 [main] DEBUG memcached.SpyMemcachedTest - key2: Deep Dark Fantatic!♂ I'm Van ♂
16:46:07.614 [main] DEBUG memcached.SpyMemcachedTest - user: User{id=123, name='assad', age=22, city='Guangzhou'}
Spring 整合 SpyMemcached
如果需要在 Spring 中整合 SpyMemcahced,SpyMemcahced 本身已經提供了一個 Memcached 裝載工廠 MemcachedClientFactoryBean ;在 Spring 上下文配置檔案中相應的配置如下:
<beans ... >
<!-- 裝載 memcachedClient bean -->
<bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean" destroy-method="destroy">
<!--設定連線服務ip,port-->
<property name="servers" value="127.0.0.1:1121" />
<!--設定連線故障模式,重新分配連線物件-->
<property name="failureMode" value="Redistribute" />
<!--設定連線失敗重連時間,單位秒-->
<property name="maxReconnectDelay" value="3" />
<!--設定型別轉化協議,轉化為二進位制,預設為 TEXT-->
<property name="protocol" value="BINARY" />
<!--設定轉化器-->
<property name="transcoder">
<bean class="net.spy.memcached.transcoders.SerializingTranscoder" p:compressionThreshold="1024" p:charset="UTF-8" />
</property>
<!--設定操作超時,單位毫秒-->
<property name="opTimeout" value="5000" />
<!--設定探測器型別-->
<property name="locatorType" value="CONSISTENT" />
<!--不使用 nagle 演算法,雖然連線速度會下降,但是更能保證穩定性-->
<property name="useNagleAlgorithm" value="false" />
</bean>
</beans>
之後在 service 層相應的服務物件自動注入 MemcachedClient 即可;XMemcached 的基本使用程式碼
使用 XMemcached,需要向專案匯入以下依賴:com.googlecode.xmemcached:xmemcached以下為 XMemcached 的基本操作程式碼,預設 memcahed ip:127.0.0.1:11211
public class XmencachedTest {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args) throws IOException, InterruptedException, MemcachedException, TimeoutException {
// 建立 memcached 客戶端
XMemcachedClient client = new XMemcachedClient(new InetSocketAddress("127.0.0.1",11211));
// 演示各種 memcached 操作
// set 操作
boolean result = client.set("key1",500,"Hello world");
log.debug("set result: " + result);
// get 操作
String key1 = (String) client.get("key1");
log.debug("key1: " + key1);
//del 操作
result = client.delete("key1");
log.debug("delete result: " + result);
// add 操作
result = client.add("key2",500,"Are you OK?");
log.debug("add result: " + result);
// gets, cas 操作
long cas = client.gets("key2").getCas();
client.cas("key2",500,"Deep Dark Fantatic",cas);
log.debug("key2: " + client.get("key2"));
// append 操作
client.append("key2","!♂ I'm Van ♂");
log.debug("key2: " + client.get("key2"));
// 演示讀寫 Java Bean
User user = new User();
user.setId(123L);
user.setName("assad");
user.setAge(22);
user.setCity("Guangzhou");
// 寫入 Java Bean
client.set(user.getId()+"",500,user);
// 獲取 Java Bean
User userGet = client.get(123L+"");
log.debug("user: " + userGet);
client.shutdown();
}
static class User implements Serializable {
private static final long serialVersionUID = 2333L;
private long id ;
private String name;
private int age;
private String city;
//getter,setter, toString
}
}
Spring 整合 XMemcached
如果需要在 Spring 中整合 XMemcahced,可以使用 XMemcached 本身提供的 XMemCachedClientBuilder 工廠類為 XMemcached 提供示工廠方法;在 Spring 上下文配置檔案中相應的配置如下
<beans ...>
<!-- 裝載 XMemcachedClientBuilder -->
<bean id="xMemcachedBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
<property name="connectionPoolSize" value="100" />
<property name="opTimeout" value="5000" />
<!--設定連線失敗是否重連-->
<property name="failureMode" value="true" />
<!--設定控制器-->
<property name="commandFactory">
<bean class="net.rubyeye.xmemcached.command.BinaryCommandFactory" />
</property>
<!--設定探測器-->
<property name="sessionLocator">
<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
</property>
<!--設定轉換器-->
<property name="transcoder">
<bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
</property>
</bean>
<!-- 裝載 XMemcacheClient-->
<bean id="memcachedClient" factory-bean="xMemcachedBuilder" factory-method="build" destroy-method="shutdown" />
</beans>
之後在 service 層相應的服務物件自動注入 MemcachedClient 即可;