memcache安装和使用

1 memcache会依赖libevent

brew install libevent

2 下载memcache

#wget http://www.memcached.org/files/memcached-1.4.22.tar.gz

然后configure;make;make install安装

3 启动:

`sudo ./memcached -p 11211 -m 64 -u shenyb -d
➜  soft  ps -ef |grep memcache
  501  4859     1   0  9:40上午 ??         0:00.16 ./memcached -p 11211 -m 64 -u shenyb -d`

可以看到memcache已经启动。
4使用java客户端连接测试
Java客户端:
目前主要有两种客户端:
<1>. https://github.com/gwhalin/Memcached-Java-Client/
<2>. http://code.google.com/p/spymemcached/会依赖spy.jar
两种差别不大,只是set时过期时间设置方式不同,效率没有测试过。
这里使用第一种:
测试代码如下:

import java.util.Date;

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

public class MemcacheUtil {
    public static void testDanga() throws Exception {
        /* 初始化SockIOPool,管理memcached的连接池 */
        String[] servers = { "127.0.0.1:11211" };
        SockIOPool pool = SockIOPool.getInstance();
        pool.setServers(servers);
        pool.setFailover(true);
        pool.setInitConn(10);
        pool.setMinConn(5);
        pool.setMaxConn(250);
        // 设置主线程睡眠时间,每30秒苏醒一次,维持连接池大小
        pool.setMaintSleep(30);
        // 关闭套接字缓存
        pool.setNagle(false);
        // 连接建立后的超时时间
        pool.setSocketTO(3000);
        pool.setAliveCheck(true);
        pool.initialize();
        /* 建立MemcachedClient实例 */
        MemCachedClient memCachedClient = new MemCachedClient();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            memCachedClient.set(i + "", "hello" + i);
        }
        for (int i = 0; i < 1000; i++) {
            System.out.println(memCachedClient.get(i + ""));
        }
        long end = System.currentTimeMillis();
        System.out.println((end - start));
        memCachedClient.set("name1", "test22",
                new Date(System.currentTimeMillis() + 3000));
        Thread.sleep(2000);
        System.out.println(memCachedClient.get("name1"));

    }

    public static void main(String[] args) {
        try {
            testDanga();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

关于设置过期时间:

 client.set(key, value, new Date(expireTime));

但这个时间如何设置,还是有一点区别,比如设置10分钟后过期,是应该设置date为System.currentTimeInMillis()+10*60*1000
还是10*60*1000
服务端是两种方式都兼容的,一个是多少秒后过期,一个是什么时候过期,
但后者因为设置时间是在客户端,存储在服务端,假如两台服务器时间差别很大,就会导致数据的过期时间和我要求的时间点不符合。

最后,memcache一般用来存储不怎么变化的数据,比如网站栏目信息,商品的属性信息,网站页脚等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱美事爱生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值