当前位置: 首页 > 工具软件 > Spymemcached > 使用案例 >

memcached的安装以及SpyMemcached的使用

常源
2023-12-01

1、Memcached的安装

  • memcached依赖于libevent库,所以先安装libevenet库

tar -xzf libevent-1.4.14b-stable.tar.gz

cd libevent-1.4.14b-stable

./configure

make

sudo make install

  • memcached的下载地址,安装步骤和libevenet一样。
  • 安装完memcached以后,执行memcached -h打印帮助信息

2、Memcached的JAVA调用

  • 建议先到网上找一个介绍Memcached的文档看一下:memcached全面剖析.pdf
  • memcached客户端使用google的spymemcached,可以直接下载,如果使用maven的话,GAV坐标如下:

    <dependency>
        <groupId>com.google.code.simple-spring-memcached</groupId>
        <artifactId>spymemcached</artifactId>
        <version>2.8.4</version>
    </dependency>

  • spymemcached的基本使用很简单:new一个MemcachedClient实例,然后调用set/add/replace/get命令即可,注意用完后要关闭客户端:调用shutdown():
MemcachedClient mc = new MemcachedClient(new InetSocketAddress(CONSTANT.MEMCACHED_ADDR, CONSTANT.MEMCACHED_PORT));

mc.set(“key”, 0, "value");

mc.shutdown();


  • pymemcached的高级用法如下:

在创建MemcachedClient的时候指定Memcached地址列表,支持Memcached集群使用;

使用异步查询asyncGet,防止因为查询不到值导致的客户端挂死问题

      // Get a memcached client connected to several servers
      // over the binary protocol
      MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),
              AddrUtil.getAddresses("server1:11211 server2:11211"));

      // Try to get a value, for up to 5 seconds, and cancel if it
      // doesn't return
      Object myObj = null;
      Future<Object> f = c.asyncGet("someKey");
      try {
          myObj = f.get(5, TimeUnit.SECONDS);
      // throws expecting InterruptedException, ExecutionException
      // or TimeoutException
      } catch (Exception e) {  /*  /
          // Since we don't need this, go ahead and cancel the operation.
          // This is not strictly necessary, but it'll save some work on
          // the server.  It is okay to cancel it if running.
          f.cancel(true);
          // Do other timeout related stuff
      }
  • 使用二进制协议如下,需要在创建MemcachedClient的时候,指定二进制链接工厂:BinaryConnectionFactory
// Get a memcached client connected to several servers with the binary protocol
MemcachedClient c=new MemcachedClient(
        new BinaryConnectionFactory(),
        AddrUtil.getAddresses("server1:11212 server2:11212"));

// Proceed to do cool stuff with memcached using the binary protocol.

key最大250个字节、key中不能有控制字符和空格、item最大1M字节、item的过期时间最大30天



 类似资料: