首页 > 代码库 > Java操作memcache

Java操作memcache

[本文出自天外归云的博客园]

准备工作

Java操作memcache需要spymemcache类库的支持,在Eclipse中修改maven项目的pom.xml文件——

添加仓库:

<repositories>      <repository>        <id>spy</id>        <name>Spy Repository</name>        <layout>default</layout>        <url>http://files.couchbase.com/maven2/</url>        <snapshots>          <enabled>false</enabled>        </snapshots>      </repository>  </repositories>

添加依赖:

<dependency>      <groupId>spy</groupId>      <artifactId>spymemcached</artifactId>      <version>2.6</version>      <scope>provided</scope>  </dependency>

添加好之后maven会自动下载好相应的类库。

操作方法

新建工具类MemcacheTool.java,操作memcache的方法代码如下:

package utils;import java.io.IOException;import java.net.InetSocketAddress;import net.spy.memcached.MemcachedClient;public class MemcacheTool {    private MemcachedClient mClient;    public MemcachedClient getmClient() {        return mClient;    }    public void setmClient(MemcachedClient mClient) {        this.mClient = mClient;    }    public MemcacheTool(String ip, int port) {        try {            setmClient(new MemcachedClient(new InetSocketAddress(ip, port)));        } catch (IOException e) {            e.printStackTrace();        }    }    public void setKey(String keyName, String keyValue) {        mClient.set(keyName, 3600, keyValue);    }    public String getKey(String keyName) {        return mClient.get(keyName).toString();    }    public static void main(String[] args) throws IOException {        String ip = "xx.xxx.xxx.xxx";        int port = xxxxx;        MemcacheTool memcacheTool = new MemcacheTool(ip, port);        String keyName = "xxxx";        System.out.println(memcacheTool.getKey(keyName));        String keyValue = "xxxx";        memcacheTool.setKey(keyName, keyValue);        System.out.println(memcacheTool.getKey(keyName));    }}

其中x掉的部分要替换:

ip:填写memcache所在服务器的ip地址;

port:填写访问memcache服务器的端口号;

keyName:要修改或获取的key的名字;

keyValue:要修改成的key值。

Java操作memcache