1.spring配置
<!-- Memcached 配置 -->
<bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
factory-method="getInstance" init-method="initialize">
<constructor-arg>
<value>neeaMemcachedPool</value>
</constructor-arg>
<property name="servers">
<list>
<value>192.168.0.215:11211</value>
<value>192.168.0.214:11211</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.danga.MemCached.MemCachedClient">
<constructor-arg>
<value>neeaMemcachedPool</value>
</constructor-arg>
</bean>
2.memcached封装调用,更具需要可以继续优化、完善。
package tzx.study.controller;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.danga.MemCached.MemCachedClient;
@Component
public class MemcachedUtils {
protected org.slf4j.Logger logger = LoggerFactory
.getLogger(this.getClass());
@Autowired
private MemCachedClient memcachedClient;
/***
* 添加缓存
*
* @param key
* @param value
* @param expiry
* 超时时间(单位:分钟)
* @throws Exception
*/
public void addCache(String key, Object value, int expiry) throws Exception {
if (StringUtils.isEmpty(key) || value == null ) {
throw new IllegalArgumentException("参数错误!");
}
// 时间换成分钟
Date date = new Date();
date.setTime(date.getTime() + expiry * 60 * 1000);
boolean isSuc = memcachedClient.set(key, value, date);
if (!isSuc) {
throw new IllegalStateException("缓存存储失败!");
}
}
/***
* 查找
*
* @param key
* 键值
* @return
* @throws Exception
*/
public Object findCache(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
throw new IllegalArgumentException("参数错误!");
}
return memcachedClient.get(key);
}
/***
* 删除
*
* @param key
* 键值
* @throws Exception
*/
public void deleteCache(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
throw new IllegalArgumentException("参数错误!");
}
memcachedClient.delete(key);
}
}