memcached应用随笔
Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。相信大家对它并不陌生,下面把我最近开发的项目中用到的一个例子分享出来,给大家一起学习。在访问memcached时,通过synchronized实现同步。在需要操作memcached的地方可以很方便地通过类CacheFactory进行。废话少说,直接贴上代码。 1import org.apache.log4j.BasicConfigurator;
2import org.apache.log4j.Logger;
3
4
5import com.danga.MemCached.MemCachedClient;
6import com.danga.MemCached.SockIOPool;
7
8
9/** *//**
10 * memcache工厂类
11 *
12 * @author fengyue
13 * @date Feb 16, 2011
14 */
15public class CacheFactory {
16private static final Logger logger = Logger.getLogger(CacheFactory.class);
17private static MemCachedClient memcache = null;
18
19
20public static MemCachedClient getCache() {
21if (memcache == null) {
22synchronized (CacheFactory.class) {
23if (memcache == null)
24getInstance();
25}
26}
27
28
29return memcache;
30}
31
32
33private static void getInstance() {
34try {
35BasicConfigurator.configure();
36String serverI = "10.185.23.17:13000";
37String[] servers = { serverI };
38SockIOPool pool = SockIOPool.getInstance();
39pool.setServers(servers);
40pool.setFailover(true);
41pool.setInitConn(10);
42pool.setMinConn(5);
43pool.setMaxConn(250);
44pool.setMaintSleep(30);
45pool.setNagle(false);
46pool.setSocketTO(3000);
47
48 www.zzzyk.com
49pool.initialize();
50memcache = new MemCachedClient();
51memcache.add("test", "test1111111111111111111");
52
53
54} catch (Exception e) {
55logger.debug("failed to init memcache");
56e.printStackTrace();
57}
58}
59
60
61
62
63public static void main(String[] argvs) {
64//往memcache存入缓存值
65CacheFactory.getCache().set("myloginkey“, "1", new Date(3 * 60 * 60 * 1000));
66//取出值
67CacheFactory.getCache().get("myloginkey");
68//删除
69CacheFactory.getCache().delete("myloginkey");
70return;
71}
72}
作者 风悦
补充:Web开发 , 其他 ,