`

memcached介绍、配置和使用(2)

阅读更多
1.安装memcache

1)  下载memcached服务端memcached-1.2.6-win32-bin.zip,地址:http://code.jellycan.com/memcached/

2)  下载java版客户端 java_memcached-release_2.6.1.zip

3)  解压缩memcached-1.2.6-win32-bin.zip到指定目录,例如:D:\memcached-1.2.6-win32 ,

在终端(即cmd命令行界面),执行'D:\memcached-1.2.6-win32\memcached.exe -d install'安装,再执行:'D:\memcached\memcached.exe -d start'启动,这样memcache就会作为windows系统服务在每 次开机时启动memcache服务。

2.导入jar包
  将java_memcached-release_2.6.1.zip解压后产生的java_memcached-release_1.6.jar加入到项目中lib文件夹下面。
3.spring与memcache集成

新建配置文件(spring级别)

新建名为spring-memcache.xml的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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"factory-method="getInstance" init-method="initialize"destroy-method="shutDown">
<constructor-arg>
<value>neeaMemcachedPool</value>
</constructor-arg>
<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">
<constructor-arg>
<value>neeaMemcachedPool</value></constructor-arg>
</bean>
</beans>

Web.xml文件中配置新建的文件

<!-- 配置spring的监听器,加载Spring配置文件-->
<context-param>  
<param-name>contextConfigLocation</param-name>   
<param-value>c
lasspath:/spring/applicationContext-common.xml,
classpath:/spring/spring-memcache.xml
</param-value>
</context-param>


修改applicationContext-common.xml配置文件。

1).添加properties配置文件(memcache.properties)去配置memcache的属性。

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:memcache.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

2).添加bean去初始化我们自己的一个spring工具类,一会进行详细解释。

<bean id="springContextHolder" class="com.hxrainbow.crm.util.SpringContextHolder"/>

Memcache配置文件

memcache.properties文件内容如下:

mcache.server=127.0.0.1\:11211
memcache.initConn=20
memcache.minConn=10
memcache.maxConn=50
memcache.maintSleep=3000
memcache.nagle=false
memcache.socketTO=3000


获得spring容器的工具类

/*** 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.**/
public class SpringContextHolder implementsApplicationContextAware{
private static ApplicationContext applicationContext;
/*** 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.*/
public voidsetApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext= applicationContext;
}
/*** 取得存储在静态变量中的ApplicationContext.*/
public staticApplicationContext 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")
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 voidcheckApplicationContext() {
if (applicationContext == null) {
throw newIllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");}
}
}

首先说一下ApplicationContextAware这个接口,这个接口中有一个方法:

void setApplicationContext(ApplicationContext applicationContext)


我们在配置文件中配置了bean的初始化,然后他就可以用于获得spring容器中的东西了。

7.memcache的工具类

public class MemcacheUtil {  
public static MemCachedClient getMemCachedClient() {   
    return SpringContextHolder.getBean("memcachedClient");}
}

8.junit测试类

public class MemcacheUtilTest { 
  static MemCachedClient memcachedClient;   
  @BeforeClass   
   public static void setUpBeforeClass() throws Exception {
   ApplicationContext ac=new ClassPathXmlApplicationContext(
new String[]{"/spring/applicationContext-common.xml","/spring/spring-memcache.xml"});  
}  
@Test   
public void s() {       
  MemCachedClient m=SpringContextHolder.getBean("memcachedClient");  
  m.set("name", "yunhui");   
  System.out.println(m.get("name"));    }}



从网上找来的测试memcache的代码
package test;
import com.meetup.memcached.MemcachedClient;
import com.meetup.memcached.SockIOPool;
import java.util.Date;

public class Test {

protected static MemcachedClient mcc = new MemcachedClient();
static {
String[] servers = { "127.0.0.1:11211" };
           //这是memcache的服务地址和端口这个static段里面其他的配置基本是不变的,所以直接用的他人的
Integer[] weights = { 3 };

// 创建一个实例对象SocketIOPool
SockIOPool pool = SockIOPool.getInstance();

// 设置Memcached Server
pool.setServers(servers);
// 设置Memcached权重
pool.setWeights(weights);

// 初始化5个连接
pool.setInitConn(5);
// 最小5个连接
pool.setMinConn(5);
// 最大250个连接
pool.setMaxConn(250);
// 一个连接最大句柄时间为6小时
pool.setMaxIdle(1000 * 60 * 60 * 6);
// 设置休眠以维持线程,它每30秒苏醒以此维护池大小
pool.setMaintSleep(30);
// Tcp的规则就是在发送一个包之前,本地机器会等待远程主机
// 对上一次发送的包的确认信息到来;这个方法就可以关闭套接字的缓存,
// 以至这个包准备好了就发;
pool.setNagle(false);
// 连接建立后对超时的控制
pool.setSocketTO(3000);
// 初始化一些值并与MemcachedServer段建立连接
pool.initialize();

// 开启压缩功能
mcc.setCompressEnable(true);
// 大于64K开始压缩
mcc.setCompressThreshold(64 * 1024);
}
private static MemcachedClient memc = new MemcachedClient();

public static void bulidCache() {
// set(key,value,Date) ,Date是一个过期时间,如果想让这个过期时间生效的话,这里传递的new Date(long
// date) 中参数date,需要是个大于或等于1000的值。
// 因为java client的实现源码里是这样实现的 expiry.getTime() / 1000 ,也就是说,如果
// 小于1000的值,除以1000以后都是0,即永不过期
mcc.set("test", "This is a test String", new Date(10000));
         // 十秒后过期
mcc.set("hzh","This is a test String",new Date(1000));
         //set有三个参数,一个是key,一个是value,一个是time

}

public static void output() {
// 从cache里取值
String value1 = (String) mcc.get("test");
String value2 = (String) mcc.get("hzh");
System.out.println(value1);
System.out.println(value2);
}

public static void main(String[] args) {
bulidCache();
output();
}

}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics