1.什么是Memcached
Memcached是一个开源、高性能、分布式的内存对象缓存系统。
Memcached是在内存中,为特定的数据(String 或 Object)
构建键值对(Key to Value)的小块数据存储
2.服务器端Memcached
因为没用过,所以在这里只是简要说明:
服务器端软件 + 服务器上上部署 Memcached Server
服务器中输入命令:
1 //安装命令 2 c:/memcached/memcached.exe -d install 3 //启动命令 4 c:/memcached/memcached.exe -d start 5 //或 6 net start "memcached Server" 7 //默认缓存大小为 64M,如不够用 找到如下注册表 8 HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/memcached Server . 9 //修改为 10 "c:/memcached/memcached.exe" -d runservice -m 51
3.如何使用?
显然,数据是需要序列化的
以下是一个他人写的例子,仅仅只是序列化内容。
1 package com.sinosuperman.memcached; 2 3 import java.io.Serializable; 4 5 6 public class User implements Serializable{ 7 8 private static final long serialVersionUID = -372274003834027815L; 9 10 String userId; 11 12 public User(String userId) { 13 super(); 14 this.userId = userId; 15 } 16 17 public String getUserId() { 18 return userId; 19 } 20 21 public void setUserId(String userId) { 22 this.userId = userId; 23 } 24 25 @Override 26 public String toString() { 27 // TODO Auto-generated method stub 28 StringBuffer sb=new StringBuffer(); 29 sb.append("userId="+this.userId); 30 return sb.toString(); 31 } 32 }
然后从客户端操作
import java.io.IOException; import java.net.InetSocketAddress; import net.spy.memcached.MemcachedClient; public class TestMemcached { public static void main(String[] args) throws IOException { //Memcached 客户端对象 值得注意的是 这里用的是SPYmemcached 客户端 MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211)); //储存 cache.set(String key, int expire , Object); for (int i = 1; i < 10; i++) { cache.set("T0001" + i, 3600, new User(i + "")); } //对应key 提取 User myObject = (User) cache.get("T00011"); System.out.println("Get object from mem :" + myObject); } }
结果如下:
1 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 2 2011-12-15 17:25:30.292 INFO net.spy.memcached.MemcachedConnection: Connection state changed for [email protected] 3 Get object from mem :userId=1
时间: 2024-10-10 07:09:53