Memcached
Java 客户端连接 Memcached & Spring 集成
Java 客户端连接 Memcached
目前连接 Memcahed 服务的
Java 客户端主要有以下 3 种方案:
- Memcached Client for Java
- SpyMemcahed
- XMemcached
其中 Memcahed 是比较早期,使用广泛的技术,优点是比较稳定;
SpyMemcahed 比
Memcached Client for Java 更加高效;
XMemcached 比 SpyMemcahed 拥有更好的并发效果;
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
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 即可;