在spring项目中 applicationContext.xml中申明
缓存配置随项目启动,交由spring管理生成
spring-xmemcached.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="memcachedClientBuilder" name="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
<!-- XMemcachedClientBuilder have two arguments.First is server list,and second is weights array. -->
<constructor-arg>
<list>
<bean class="java.net.InetSocketAddress">
<constructor-arg>
<value>localhost</value>
</constructor-arg>
<constructor-arg>
<value>11211</value>
</constructor-arg>
</bean>
</list>
</constructor-arg>
<constructor-arg>
<list>
<value>1</value>
</list>
</constructor-arg>
<property name="connectionPoolSize" value="30"></property>
<property name="commandFactory">
<bean class="net.rubyeye.xmemcached.command.TextCommandFactory"></bean>
</property>
<property name="sessionLocator">
<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"></bean>
</property>
<property name="transcoder">
<bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
</property>
</bean>
<!-- Use factory bean to build memcached client -->
<bean id="memcachedClient" name="memcachedClient" factory-bean="memcachedClientBuilder" factory-method="build" destroy-method="shutdown"/>
</beans>
XMemcachedHelper.java
package xueshenghui.helper.cache;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import xueshenghui.constants.emall.cache.CacheConstant;
import xueshenghui.constants.emall.cache.api3.EmDaixiaoApi3CacheConstant;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
/**
* XMemcached 服务器缓存数据
*
* @author Yangyiyong
*
*/
@Component
public class XMemcachedHelper {
private static Logger logger = Logger.getLogger(XMemcachedHelper.class);
private static final int defaultWeight = 0; // 默认权重
private MemcachedClient client ;
public MemcachedClient getClient() {
return client;
}
public void setClient(MemcachedClient client) {
this.client = client;
}
private static final Map<String, String> keyMap = new HashMap<String, String>(); // 可存储的key值
static {
Field[] fields01 = CacheConstant.class.getDeclaredFields();
if(null != fields01 && fields01.length > 0){
for(Field field : fields01){
keyMap.put(field.getName(), null);
}
}
Field[] fields02 = EmDaixiaoApi3CacheConstant.class.getDeclaredFields();
if(null != fields02 && fields02.length > 0){
for(Field field : fields02){
keyMap.put(field.getName(), null);
}
}
}
/**
* 校验状态
*
* @return
*/
private boolean checkClientStatus(){
boolean flag = false;
if(null != client && !client.isShutdown()){
flag = true;
}
return flag;
}
/**
* 校验是否存在key值
*
* @param key
* @return
*/
private boolean checkKey(String key){
return keyMap.containsKey(key);
}
/**
* flushAll 清空所有,请谨慎使用
*
*/
public void flushAll(){
if(checkClientStatus()){
try {
client.flushAll();
} catch (TimeoutException e) {
logger.error("TimeoutException flushAll :".concat(e.getMessage()));
} catch (InterruptedException e) {
logger.error("InterruptedException flushAll :".concat(e.getMessage()));
} catch (MemcachedException e) {
logger.error("MemcachedException flushAll :".concat(e.getMessage()));
}
}
}
/**
* 删除某个key
*
* @param key
* @return
*/
public boolean deleteKey(String key){
boolean flag = false;
if(checkClientStatus() && checkKey(key)){
try {
flag = client.delete(key);
} catch (TimeoutException e) {
logger.error("TimeoutException deleteKey key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (InterruptedException e) {
logger.error("InterruptedException deleteKey key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (MemcachedException e) {
logger.error("MemcachedException deleteKey key=".concat(key).concat(" :").concat(e.getMessage()));
}
}
return flag;
}
/**
* 存储值
*
* @param key
* @param val
* @return
*/
public boolean setVal(String key , Object val){
boolean flag = false;
if(checkClientStatus() && checkKey(key) && null != val){
try {
Object obj = client.get(key);
if(null == obj){
flag = client.set(key, defaultWeight, val);
}else{
flag = client.replace(key, defaultWeight, val);
}
} catch (TimeoutException e) {
logger.error("TimeoutException setVal key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (InterruptedException e) {
logger.error("InterruptedException setVal key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (MemcachedException e) {
logger.error("MemcachedException setVal key=".concat(key).concat(" :").concat(e.getMessage()));
}
}
return flag;
}
/**
* 获取值
*
* @param key
* @return
*/
public Object getVal(String key){
if(checkClientStatus() && checkKey(key)){
try {
return client.get(key);
} catch (TimeoutException e) {
logger.error("TimeoutException getVal key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (InterruptedException e) {
logger.error("InterruptedException getVal key=".concat(key).concat(" :").concat(e.getMessage()));
} catch (MemcachedException e) {
logger.error("MemcachedException getVal key=".concat(key).concat(" :").concat(e.getMessage()));
}
}
return null;
}
}
在spring中使用 @Cacheable实现缓存
将数据放入缓存 @Cacheable(value = "employee")
- MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("10.10.1.1:11211 10.10.1.2:11211"));
- MemcachedClient memcachedClient = builder.build();
但是上一段代码,如何用spring初始化呢?
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
- <!-- 配置文件 -->
- <bean id="configproperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
- <property name="locations">
- <list>
- <value>classpath:application.properties</value>
- </list>
- </property>
- </bean>
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
- <property name="properties" ref="configproperties" />
- </bean>
- <!-- memcached初始化 -->
- <bean id="builder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
- <constructor-arg>
- <bean class="net.rubyeye.xmemcached.utils.AddrUtil" factory-method="getAddresses">
- <constructor-arg value="${memached.host}" />
- </bean>
- </constructor-arg>
- </bean>
- <bean id="memcachedClient" class="net.rubyeye.xmemcached.MemcachedClient" factory-bean="builder" factory-method="build" destroy-method="shutdown" />
- </beans>