搭建缓存服务器
5.1搭建准备
1、安装memcached需先安装libevent,故需要准备libeventlinux安装包:libevent-1.4.14b-stable.tar.gz。
2、准备安装memcachedlinux安装包:memcached-1.4.10.tar.gz
5.2搭建
1、用用户登录主机,创建一个临时目录:临时目录。
2、将libevent安装包和memcached安装包上传到临时目录下。
3、安装libevent
找到libevent安装包存放的目录,输入命令:cd临时目录
将libevent安装包进行解压,输入命令:tarzvxflibevent-1.4.14b-stable.tar.gz
进入到libevent目录中,输入命令:cdlibevent-1.4.14b-stable
设置安装路径,输入命令:./configure–prefix=/usr
进行安装,输入命令:make
进行初始安装,输入命令:makeinstall
测试libevent是否安装成功,输入命令:ls-al/usr/lib|greplibevent,将会显示下面内容
lrwxrwxrwx1rootroot212012-08-0315:37libevent-1.4.so.2->libevent-1.4.so.2.2.0
-rwxr-xr-x1rootroot4008162012-08-0315:37libevent-1.4.so.2.2.0
-rw-r--r--1rootroot6409782012-08-0315:37libevent.a
lrwxrwxrwx1rootroot262012-08-0315:37libevent_core-1.4.so.2->libevent_core-1.4.so.2.2.0
-rwxr-xr-x1rootroot1443972012-08-0315:37libevent_core-1.4.so.2.2.0
-rw-r--r--1rootroot2385402012-08-0315:37libevent_core.a
-rwxr-xr-x1rootroot9882012-08-0315:37libevent_core.la
lrwxrwxrwx1rootroot262012-08-0315:37libevent_core.so->libevent_core-1.4.so.2.2.0
lrwxrwxrwx1rootroot272012-08-0315:37libevent_extra-1.4.so.2->libevent_extra-1.4.so.2.2.0
-rwxr-xr-x1rootroot3166802012-08-0315:37libevent_extra-1.4.so.2.2.0
-rw-r--r--1rootroot4963162012-08-0315:37libevent_extra.a
-rwxr-xr-x1rootroot9952012-08-0315:37libevent_extra.la
lrwxrwxrwx1rootroot272012-08-0315:37libevent_extra.so->libevent_extra-1.4.so.2.2.0
-rwxr-xr-x1rootroot9532012-08-0315:37libevent.la
lrwxrwxrwx1rootroot212012-08-0315:37libevent.so->libevent-1.4.so.2.2.0
4、安装memcached
找到memcached安装包存放的目录,输入命令:cd临时目录
将memcached安装包进行解压,输入命令:tarzvxfmemcached-1.4.10.tar.gz
进入memcached目录,输入命令:cdmemcached-1.4.10
指定libevent安装目录,输入命令:./configure–with-libevent=/usr
进行安装,输入命令:make
进行初始安装,输入命令:makeinstall
5、启动memcached
启动memcached命令为:#/usr/local/bin/memcached-d-m10-uroot-lip-p端口号-c256-P/目录/memcached.pid
-d选项是启动一个守护进程,-m是分配给Memcache使用的内存数量,单位是MB,我这里是10MB,-u是运行Memcache的用户,我这里是root,-l是监听的服务器IP地址,如果有多个地址的话,我这里指定了服务器的IP地址192.168.0.200,-p是设置Memcache监听的端口,我这里设置了12000,最好是1024以上的端口,-c选项是最大运行的并发连接数,默认是1024,我这里设置了256,按照你服务器的负载量来设定,-P是设置保存Memcache的pid文件,我这里是保存在/tmp/memcached.pid
5.3测试
1、编写一个将一个值存入缓存中,再从缓存中获取,最后再将缓存中删除该值的程序,该程序需添加xmemcached-1.2.6.2.jar。
importnet.rubyeye.xmemcached.MemcachedClient;
importnet.rubyeye.xmemcached.MemcachedClientBuilder;
importnet.rubyeye.xmemcached.XMemcachedClientBuilder;
importnet.rubyeye.xmemcached.utils.AddrUtil;
publicclassTestMain{
publicstaticvoidmain(Stringargs[]){
try{
MemcachedClientmc=null;
MemcachedClientBuilderbuilder=newXMemcachedClientBuilder(
AddrUtil.getAddresses("IP:端口号"));//获取build
mc=builder.build();//获取缓存服务器
booleanflag=mc.add("helloworld",3,"helloworld");//存入缓存中
System.out.println("value=="+mc.get("helloworld"));//从缓存中获取值
System.out.println("flag=="+flag);
flag=mc.add("helloworld",3,"helloworld");//添加到缓存中会失败
System.out.println("flag=="+flag);
mc.delete("helloworld");//从缓存中删除该键+
}catch(Exceptione){
e.printStackTrace();
}
}
}
2、启动该程序,如程序正常运行,且结果与预期结果一致,则缓存启动成功。