Memcached的安装和使用
What is Memcached?
Memcached是一个高性能的分布式的内存对象缓存系统,用于动态Web应用以减轻数据库负载。Memcached是在内存中,为特定数据(字符串或对象)构建key-value的小块据存储。
它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态、数据库驱动网站的速度。
Memcached基于一个存储键/值对的hashmap。
如何配置memcached呢?
1
到memcached官方网站下载memcached,即memcached.exe文件
2
下载下来的Windows版本解压到C:/memcached/
在控制台输入命令安装:
c:/memcached/memcached.exe -d install |
c:/memcached/memcached.exe -d start 或使用:net start"memcached Server" |
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/memcached Server .
将其内容修改为:
“C:/memcached/memcached.exe” -d runservice -m 512 |
4. 下载Memcached的客户端API包
下载地址:http://spymemcached.googlecode.com/files/memcached-2.5.jar
5. 编写一个Java数据类
package com.sinosuperman.memcached; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = -372274003834027815L; String userId; public User(String userId) { super(); this.userId = userId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); sb.append("userId="+this.userId); return sb.toString(); }6. 编写一个Memcached的客户端
<span style="font-size:14px;">package com.sinosuperman.memcached; import java.io.IOException; import java.net.InetSocketAddress; import net.spy.memcached.MemcachedClient; public class TestMemcached { public static void main(String[] args) throws IOException { MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211)); for (int i = 1; i < 10; i++) { cache.set("T0001" + i, 3600, new User(i + "")); } User myObject = (User) cache.get("T00011"); System.out.println("Get object from mem :" + myObject); } } </span>
7. 运行测试
运行结果应该如下:
- 2011-12-15 17:25:30.276 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
- 2011-12-15 17:25:30.292 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@c62080
- Get object from mem :userId=1
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。