whalin java操作memcache

本文主要介绍通过whalin进行memcache的基本操作。 
这种方式需要注意的是key是经过urlencoder的,也就是说在telnet中进行查找的时候需要对你的key进行urlencoder。

好,下面介绍如何使用。

1、引入pom依赖

<dependency>
   <groupId>com.whalin</groupId>
   <artifactId>Memcached-Java-Client</artifactId>
   <version>3.0.2</version>
</dependency>

2、初始化

public static MemCachedClient memcachedClient;

static {
    try {
        String[] servers = {"192.168.0.12:11211"};
        SockIOPool pool = SockIOPool.getInstance();
        pool.setServers(servers);
        pool.setFailover(true);
        pool.setInitConn(10);
        pool.setMinConn(5);
        pool.setMaxConn(250);
        pool.setMaintSleep(30);
        pool.setNagle(false);
        pool.setSocketTO(3000);
        pool.setAliveCheck(true);
        pool.initialize();
        memcachedClient = new MemCachedClient();
        System.out.println("Connection to server sucessful.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

3、set和get方法。

@RequestMapping("/set")
    public boolean setkey(String key, String value) {
        return memcachedClient.set(key, value);
    }

    @RequestMapping("/get")
    public Object getkey(String key) {
        return memcachedClient.get(key);
    }

这里比较方便的是,set方法和get方法。这两个方法封装的非常好。简洁,使用。set的时候直接指定key和value就行。

在get的时候只需要指定key就可以,然后可以直接返回对象,这样就可以把对象序列化存储到memcache中了。


再次强调whalin这个jar包遇到特殊字符会进行转义的,转义的方法就是urlencode。

猜你喜欢

转载自blog.csdn.net/wild46cat/article/details/79999093