Java client 访问 memcached

在测试项目中引入了memcached作为缓存层,以下是memcached的缓存配置和调用过程。

  • linux下memcached安装过程

直接参考以前的博文linux下安装memcached过程  不再详细介绍

  • java客户端访问memcached的jar包

在2.6及以前版本使用的是java_memcached-release_2.6.3.jar,3.0以上版本使用memcached-Java-Client-3.0.2.jar,下载地址为http://mvnrepository.com/artifact/com.whalin/Memcached-Java-Client。这两个版本差异较大,官方说法是由于danga的域名不属于他们所有,所以现在修改了类包名称。这是官方的wiki有相关的解释:https://github.com/gwhalin/Memcached-Java-Client/wiki

  • memcached-Java-Client的依赖包

memcached-Java-Client-3.0.2.jar 需要以下一些包,

1、commons-pool2-2.4.1.jar依赖包,下载地址http://mvnrepository.com/artifact/org.apache.commons/commons-pool2

2、junit

3、slf4j

  • application-Context.xml中 配置支持memcached
	<bean id="memcachedPool" class="com.schooner.MemCached.SchoonerSockIOPool"
factory-method="getInstance" init-method="initialize">
<constructor-arg>
<value>neeaMemcachedPool</value>
</constructor-arg>
<property name="servers">
<list>
<value>memcached安装的服务器ip地址:memcached的监听端口</value>
</list>
</property>
<property name="initConn">
<value>20</value>
</property>
<property name="minConn">
<value>10</value>
</property>
<property name="maxConn">
<value>50</value>
</property>
<property name="nagle">
<value>false</value>
</property>
<property name="socketTO">
<value>3000</value>
</property>
</bean> <bean id="memcachedClient" class="com.whalin.MemCached.MemCachedClient">
<constructor-arg>
<value>neeaMemcachedPool</value>
</constructor-arg>
</bean>
  • memcached操作类
public class Memcached {

	static MemCachedClient  cachedClient;

	private Memcached(){

	}

	public static void init()
{
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:setup/applicationContext.xml");
cachedClient = (MemCachedClient)ctx.getBean("memcachedClient"); } public static Object get(String key) {
return cachedClient.get(key);
} public static boolean add(String key, Object value) {
return cachedClient.add(key, value);
} public static boolean add(String key, Object value, Integer expire) {
return cachedClient.add(key, value, expire);
} public static boolean set(String key, Object value) {
return cachedClient.set(key, value);
} public static boolean set(String key, Object value, Integer expire) {
return cachedClient.set(key, value, expire);
} public static boolean replace(String key, Object value) {
return cachedClient.replace(key, value);
} public static boolean replace(String key, Object value, Integer expire) {
return cachedClient.replace(key, value, expire);
} public static boolean delete(String key){
return cachedClient.delete(key);
}
}
  • 调用测试
      Memcached.set("memcached", "测试");
System.out.println("memcached缓存————————="+ Memcached.get("memcached"));
上一篇:【leetcode】Single Number && Single Number II(ORZ 位运算)


下一篇:Single Number,Single Number II