朋友公司开发的项目要用到缓存,于是叫我推荐一个,我说我们公司在用Memcached,然后就问了我一堆关于Memcached的问题,直接把我问的无言了,因为虽然项目用到了,但是我自己却没搞过这个,只是知道有这么个东西存在,唉…
准备工作:
1.从http://splinedancer.com/memcached-win32/下载Memcached for Windows。解压至任意目录(如C:\memcached),然后执行如下DOS命令进行安装:

C:\memcached>memcached.exe -d install
C:\memcached>memcached.exe -d start

2.从https://github.com/gwhalin/Memcached-Java-Client下载Memcached相关的jar包。
测试程序:

package webshell.cc;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemCachedTest {

    private static MemCachedClient mcc = new MemCachedClient();

    static {
        String[] servers = {"192.168.0.107:11211"};
        //创建一个连接池
        SockIOPool pool = SockIOPool.getInstance();
        //设置缓存服务器
        pool.setServers(servers);
        //设置初始化连接数,最小连接数,最大连接数以及最大处理时间
        pool.setInitConn(50);
        pool.setMinConn(50);
        pool.setMaxConn(500);
        pool.setMaxIdle(1000 * 60 * 60);
        //设置主线程睡眠时间,每30秒苏醒一次,维持连接池大小
        pool.setMaintSleep(30);
        //关闭套接字缓存
        pool.setNagle(false);
        //连接建立后的超时时间
        pool.setSocketTO(3000);
        //连接建立时的超时时间
        pool.setSocketConnectTO(0);
        //初始化连接池
        pool.initialize();
    }

    protected MemCachedTest(){

    }

    public static MemCachedClient getInstance(){
        return mcc;
    }

    public static void main(String[] args) {

        MemCachedClient cache = MemCachedTest.getInstance();
        User u1 = new User();
        u1.setName("Neeke");
        u1.setBlog("http://www.ineeke.com");
        cache.add("neeke", u1);

        User u2 = (User) cache.get("neeke");
        System.out.println("name=" + u2.getName());
        u2.setName("other");
        cache.replace("neeke", u2);

        u2 = (User) cache.get("neeke");
        System.out.println("name=" + u2.getName());
    }
}

转载请注明来自WebShell'S Blog,本文地址:https://www.webshell.cc/865.html