今天闲来无事,因为工作中要用到缓存,这里决定使用Memcache,所以利用周末,在家里做了个demo,发表出来希望对大家有用。
1, 开始肯定是下载需要的文件了,这里就下载附件里的文件就好,我也是在网上down的,放这好找。然后我们安装一下Memcache服务器,找到解压的memcached-1.2.1-win32,启动cmd ,进入解压目录,输入命令 D
:\memcached-1.2.6-win32\memcached.exe -d install.
然后再键入命令'D:\memcached\memcached.exe -d start'
启动,这样memcache就会作为windows系统服务在每次开机时启动memcache服务。
2,下面我们开始在使用java进行配置开发。添加Spring功能。在web.xml中添加配置。
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext-common.xml, classpath:/spring/spring-memcache.xml </param-value> </context-param>
3,在src下新建spring目录,并新建applicationContext-common.xml和spring-memcache.xml。内容分别如下。
applicationContext-common.xml
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:memcache.properties</value> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="springContextHolder" class="com.hxrainbow.crm.util.SpringContextHolder"/> </beans>
spring-memcache.xml
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool" factory-method="getInstance" init-method="initialize" destroy-method="shutDown"> <property name="servers"> <list> <value>${memcache.server}</value> </list> </property> <property name="initConn"> <value>${memcache.initConn}</value> </property> <property name="minConn"> <value>${memcache.minConn}</value> </property> <property name="maxConn"> <value>${memcache.maxConn}</value> </property> <property name="maintSleep"> <value>${memcache.maintSleep}</value> </property> <property name="nagle"> <value>${memcache.nagle}</value> </property> <property name="socketTO"> <value>${memcache.socketTO}</value> </property> </bean> <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient"> </bean> </beans>
在配置文件中我们会看到memcache.properties,jdbc.properties和springContextHolder。
他们的内容分别是:
memcache.properties memcache.server=127.0.0.1:11211 memcache.initConn=20 memcache.minConn=10 memcache.maxConn=50 memcache.maintSleep=3000 memcache.nagle=false memcache.socketTO=3000
jdbc.properties
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
*
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
**/
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
*
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
/**
*
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
/**
*
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
*
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*
* 如果有多个Bean符合Class, 取出第一个.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
Map beanMaps = applicationContext.getBeansOfType(clazz);
if (beanMaps != null && !beanMaps.isEmpty()) {
return (T) beanMaps.values().iterator().next();
} else {
return null;
}
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException(
"applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
配置文件我们写完了,下面我们开始测试使用。
做Bean类
import java.io.Serializable;
public class Bean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String bean = "{name:"+this.getName()+",age:"+this.getAge()+"}";
return bean;
}
}
做测试使用类:
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemcacheUtilTest {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{"src/spring/spring-memcache.xml","src/spring/applicationContext-common.xml"});
SockIOPool s =SpringContextHolder.getBean("memcachedPool");
System.out.println("s="+s.getInitConn());
MemCachedClient mc = (MemCachedClient) ctx.getBean("memcachedClient");
//开始设值
mc.set("name", " string ");
mc.set("int", 5);
mc.set("double", 5.5);
Bean bean = new Bean();
bean.setAge(21);
bean.setName("名字");
mc.set("bean", bean);
List<Bean> data = new ArrayList<Bean>();
for(int i=0;i<3;i++)
{
Bean xbean = new Bean();
xbean.setAge(i);
xbean.setName("test_"+i);
data.add(xbean) ;
}
mc.set("data", data);
try{
Thread.sleep(50);
//开始取值
String name =(String) mc.get("name");
int i = (Integer) mc.get("int");
double d = (Double) mc.get("double") ;
Bean b = (Bean) mc.get("bean") ;
data = (List<Bean>) mc.get("data") ;
System.out.println("字符串:"+name);
System.out.println("数字型:"+i);
System.out.println("双精度:"+d);
System.out.println("bean toString :"+b.toString());
System.out.println("data toString :"+data.toString());
//开始删除值
System.out.println("开始删除 :》》》》》》》》》");
mc.delete("name");
mc.delete("int");
mc.delete("double");
mc.delete("bean");
String name_d =(String) mc.get("name");
int i_d = (Integer) mc.get("int");
double d_d = (Double) mc.get("double") ;
Bean b_d = (Bean) mc.get("bean") ;
System.out.println("字符串:"+name_d);
System.out.println("数字型:"+i_d);
System.out.println("双精度:"+d_d);
System.out.println("bean toString :"+b_d.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
运行一下,看看结果吧。具体可参考java_memcached-release_1.6\doc\HOWTO.txt.注意Bean要实现序列化。