您的位置:首页 > 数据库 > Memcache

Spring+Xmemcached 使用.

2016-12-17 00:00 302 查看
Xmemcache---java 连接memcached缓存服务器的客户端.

这里其实可以不用spring来粘合.但是使用spring来配置属性也是可以的.

那就是写一个单例工厂类,而参数则可以在spring的xml配置文件中单独配置.

在通过spring的 factoryBean来产生所需要的bean.

在使用这个bean注入到需要使用的MemcachedClient接口.就可以实现缓存的读写.

第一步,创建产生xclient的factoryBean.

package com.xmemcached;

import java.io.IOException;

import com.google.code.yanf4j.config.Configuration;

import net.rubyeye.xmemcached.CommandFactory;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.MemcachedSessionLocator;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class XMemcachedClientFactoryBean {

private MemcachedClient client;
// 这里定义需要配置的参数,然后在使用spring的xml时候进行覆盖.达到定制客户端的目的
private String servers;
private long timeout = 2000L;
private CommandFactory commandFactory = new BinaryCommandFactory();
private Configuration configuration = XMemcachedClientBuilder.getDefaultConfiguration();
private MemcachedSessionLocator sessionLocator = new KetamaMemcachedSessionLocator();

public void init() throws Exception {

if (client == null) {
synchronized (client) {
if (client == null) {
client = createClient();
}
}
}
}

// 创建客户端
private MemcachedClient createClient() throws IOException {

// 这里加载已经配置好的成员变量,返回定制的客户端.
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(servers));
builder.setCommandFactory(commandFactory);
// 配置
builder.setConfiguration(configuration);
// 连接池
builder.setConnectionPoolSize(10);
// 会话
builder.setSessionLocator(sessionLocator);
// 对于重新愈合的session,把其重新加到可用队列中
builder.setEnableHealSession(true);
// 10s连接
builder.setConnectTimeout(10000L);
// 这里不使用失败模式,在节点请求失败后,可以迅速把此节点剔除,从而使用另外的节点
builder.setFailureMode(false);
MemcachedClient xClient = builder.build();
xClient.setOpTimeout(timeout);
return xClient;
}

//这个方法用于生成对应的bean.
public MemcachedClient getClient() {
return client;
}

public void setClient(MemcachedClient client) {
this.client = client;
}

public String getServers() {
return servers;
}

public void setServers(String servers) {
this.servers = servers;
}

public long getTimeout() {
return timeout;
}

public void setTimeout(long timeout) {
this.timeout = timeout;
}

public CommandFactory getCommandFactory() {
return commandFactory;
}

public void setCommandFactory(CommandFactory commandFactory) {
this.commandFactory = commandFactory;
}

public Configuration getConfiguration() {
return configuration;
}

public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}

public MemcachedSessionLocator getSessionLocator() {
return sessionLocator;
}

public void setSessionLocator(MemcachedSessionLocator sessionLocator) {
this.sessionLocator = sessionLocator;
}

}

第二步:配置注入的参数,产生bean.

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
<description>spring-context加载xmemcached配置</description>

<bean name="xmemFactoryBean" class="com.xmemcached.XMemcachedClientFactoryBean" init-method="init" destroy-method="destroy">
<!-- 属性注入 -->
<property name="servers" value="localhost:123456" />
<property name="timeout" value="5000"></property>
<property name="sessionLocator">
<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
</property>
</bean>
<!-- 产生的bean -->
<bean name="myClient" factory-bean="xmemFactoryBean" factory-method="getClient" />

</beans>

第三步,写测试类.

package com.xmemcached;

import java.util.concurrent.TimeoutException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:context.xml" })
public class XMemcachedTest {

@Autowired
@Qualifier("myClient")
private MemcachedClient client;

private static final Logger log = LoggerFactory.getLogger(XMemcachedTest.class);

//测试
@Test
public  void test(String[] args) {
set("hello", 30, "nihao");
System.out.println(get("hello"));
}

// 添加缓存
public <T> boolean set(final String key, int expireTimeInSecond, final T value) {
try {
return client.set(key, expireTimeInSecond, value);
} catch (TimeoutException e) {
log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
} catch (InterruptedException e) {
log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
} catch (MemcachedException e) {
log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
}
return false;
}

// 获取缓存
public <T> T get(String key) {
try {
return client.get(key);
} catch (TimeoutException e) {
log.error("{key: '" + key + "'}", e);
} catch (InterruptedException e) {
log.error("{key: '" + key + "'}", e);
} catch (MemcachedException e) {
log.error("{key: '" + key + "'}", e);
} catch (Throwable e) {
log.error("{key: '" + key + "'}", e);
}
return null;
}
}

另外,这里可配置的东西挺多的,可以自定义实现序列化等等.简单实用的话,可以不用管这些,但是做框架封装时须要考虑取舍.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring XMemcached