`

memcached client -- memcached client for java使用

阅读更多
来源:http://blog.csdn.net/gtuu0123/article/details/4897805


memcached client for java是另一个memcached的java客户端

http://www.whalin.com/memcached/#download



代码:

(1)MemcachedServer -- memcached的服务器

[java] view plaincopyprint?
01.public class MemcachedServer { 
02.     
03.    private String address; 
04.    private int port; 
05.    private int weight; 
06.     
07.    public MemcachedServer(String address, int port, int weight) { 
08.        this.address = address; 
09.        this.port = port; 
10.        this.weight = weight; 
11.    } 
12.     
13.    public String getAddress() { 
14.        return address; 
15.    } 
16.     
17.    public int getPort() { 
18.        return port; 
19.    } 
20.     
21.    public int getWeight() { 
22.        return weight; 
23.    } 
24.     
25.    public String toString() { 
26.        return address + ":" + port + "," + weight; 
27.    } 
28.     
29.} 
public class MemcachedServer {

private String address;
private int port;
private int weight;

public MemcachedServer(String address, int port, int weight) {
this.address = address;
this.port = port;
this.weight = weight;
}

public String getAddress() {
return address;
}

public int getPort() {
return port;
}

public int getWeight() {
return weight;
}

public String toString() {
return address + ":" + port + "," + weight;
}

}




(2)MemcachedException

[java] view plaincopyprint?
01.@SuppressWarnings("serial") 
02.public class MemcachedException extends Exception { 
03.     
04.    public MemcachedException() { 
05.        super(); 
06.    } 
07.     
08.    public MemcachedException(Throwable t) { 
09.        super(t); 
10.    } 
11.     
12.    public MemcachedException(String error) { 
13.        super(error); 
14.    } 
15.     
16.    public MemcachedException(String error, Throwable t) { 
17.        super(error, t); 
18.    } 
19.     
20.} 
@SuppressWarnings("serial")
public class MemcachedException extends Exception {

public MemcachedException() {
super();
}

public MemcachedException(Throwable t) {
super(t);
}

public MemcachedException(String error) {
super(error);
}

public MemcachedException(String error, Throwable t) {
super(error, t);
}

}



(3)PoolDefaultProperties  --  memcached池初始化参数

[java] view plaincopyprint?
01.import java.util.Properties; 
02. 
03.public class PoolDefaultProperties extends Properties { 
04.     
05.    private static final long serialVersionUID = -7630655479181446040L; 
06. 
07.    public PoolDefaultProperties() { 
08.        super(); 
09.        initDefault(); 
10.    } 
11.     
12.    private void initDefault() { 
13.        initConn(); 
14.        initMainSleep(); 
15.        initTCP(); 
16.        initFailover(); 
17.        initAliveCheck(); 
18.    } 
19.     
20.    protected void initConn() { 
21.        setProperty("initConn", "10"); 
22.        setProperty("minConn", "10"); 
23.        setProperty("maxConn", "20"); 
24.        setProperty("maxIdle", String.valueOf(1000 * 60 * 30)); 
25.    } 
26.     
27.    protected void initMainSleep() { 
28.        setProperty("maintSleep", String.valueOf(1000 * 5)); 
29.    } 
30.     
31.    protected void initTCP() { 
32.        setProperty("nagle", "false"); 
33.        setProperty("socketTO", String.valueOf(1000 * 3)); 
34.        setProperty("socketConnectTO", String.valueOf(1000 * 3)); 
35.    } 
36.     
37.    protected void initFailover() { 
38.        setProperty("failover", "true"); 
39.        setProperty("failback", "true"); 
40.    } 
41.     
42.    protected void initAliveCheck() { 
43.        setProperty("aliveCheck", "true"); 
44.    } 
45.     
46.} 
import java.util.Properties;

public class PoolDefaultProperties extends Properties {

private static final long serialVersionUID = -7630655479181446040L;

public PoolDefaultProperties() {
super();
initDefault();
}

private void initDefault() {
initConn();
initMainSleep();
initTCP();
initFailover();
initAliveCheck();
}

protected void initConn() {
setProperty("initConn", "10");
setProperty("minConn", "10");
setProperty("maxConn", "20");
setProperty("maxIdle", String.valueOf(1000 * 60 * 30));
}

protected void initMainSleep() {
setProperty("maintSleep", String.valueOf(1000 * 5));
}

protected void initTCP() {
setProperty("nagle", "false");
setProperty("socketTO", String.valueOf(1000 * 3));
setProperty("socketConnectTO", String.valueOf(1000 * 3));
}

protected void initFailover() {
setProperty("failover", "true");
setProperty("failback", "true");
}

protected void initAliveCheck() {
setProperty("aliveCheck", "true");
}

}




(4)MemcachedPool  --  memcached池

[java] view plaincopyprint?
01.import java.lang.reflect.InvocationTargetException; 
02.import java.util.Iterator; 
03.import java.util.List; 
04.import java.util.Properties; 
05.import java.util.Set; 
06. 
07.import org.apache.commons.beanutils.ConvertUtils; 
08.import org.apache.commons.beanutils.PropertyUtils; 
09.import org.apache.commons.logging.Log; 
10.import org.apache.commons.logging.LogFactory; 
11. 
12.import com.danga.MemCached.SockIOPool; 
13. 
14.public class MemcachedPool { 
15.     
16.    private static final Log logger = LogFactory.getLog(MemcachedPool.class); 
17.     
18.    private static Properties POOL_DEFAULT_VALUE = new PoolDefaultProperties(); 
19.     
20.    private static MemcachedPool pool = new MemcachedPool(); 
21.     
22.    private MemcachedPool() {} 
23.     
24.    public static MemcachedPool getInstance() { 
25.        return pool; 
26.    } 
27.     
28.    public void initPool(List<MemcachedServer> servers) throws MemcachedException { 
29.        initPool(servers, POOL_DEFAULT_VALUE); 
30.    } 
31.     
32.    public void initPool(List<MemcachedServer> servers, Properties props) throws MemcachedException { 
33.        SockIOPool sockIOPool = SockIOPool.getInstance(); 
34.         
35.        //server & weight  
36.        sockIOPool.setServers(getServer(servers)); 
37.        sockIOPool.setWeights(getWeight(servers)); 
38.         
39.         
40.        //bean props  
41.        Set keys = props.keySet(); 
42.        Iterator keyIter = keys.iterator(); 
43.        while (keyIter.hasNext()) { 
44.            String key = (String)keyIter.next(); 
45.            String value = props.getProperty(key); 
46.            if (value == null) { 
47.                value = POOL_DEFAULT_VALUE.getProperty(key); 
48.            } 
49.            try { 
50.                Class type = PropertyUtils.getPropertyType(sockIOPool, key); 
51.                logger.debug("Type=" + type + ";Key=" + key + ";Value=" + value); 
52.                Object val = ConvertUtils.convert(value, type); 
53.                PropertyUtils.setSimpleProperty(sockIOPool, key, val); 
54.            } catch (IllegalAccessException e) { 
55.                throw new MemcachedException("Init Pool Fail", e); 
56.            } catch (InvocationTargetException e) { 
57.                throw new MemcachedException("Init Pool Fail", e); 
58.            } catch (NoSuchMethodException e) { 
59.                throw new MemcachedException("Init Pool Fail", e); 
60.            } 
61.        } 
62.        sockIOPool.initialize(); 
63.    } 
64.     
65.    private Integer[] getWeight(List<MemcachedServer> weigths) { 
66.        Integer[] w = new Integer[weigths.size()]; 
67.        for (int i = 0; i < weigths.size(); i++) { 
68.            w[i] = weigths.get(i).getWeight(); 
69.        } 
70.        return w; 
71.    } 
72.     
73.    private String[] getServer(List<MemcachedServer> servers) { 
74.        String[] s = new String[servers.size()]; 
75.        for (int i = 0; i < servers.size(); i++) { 
76.            MemcachedServer server = servers.get(i); 
77.            s[i] = server.getAddress() + ":" + server.getPort(); 
78.        } 
79.        return s; 
80.    } 
81.     
82.     
83.} 
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.danga.MemCached.SockIOPool;

public class MemcachedPool {

private static final Log logger = LogFactory.getLog(MemcachedPool.class);

private static Properties POOL_DEFAULT_VALUE = new PoolDefaultProperties();

private static MemcachedPool pool = new MemcachedPool();

private MemcachedPool() {}

public static MemcachedPool getInstance() {
return pool;
}

public void initPool(List<MemcachedServer> servers) throws MemcachedException {
initPool(servers, POOL_DEFAULT_VALUE);
}

public void initPool(List<MemcachedServer> servers, Properties props) throws MemcachedException {
SockIOPool sockIOPool = SockIOPool.getInstance();

//server & weight
sockIOPool.setServers(getServer(servers));
sockIOPool.setWeights(getWeight(servers));


//bean props
Set keys = props.keySet();
Iterator keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = (String)keyIter.next();
String value = props.getProperty(key);
if (value == null) {
value = POOL_DEFAULT_VALUE.getProperty(key);
}
try {
Class type = PropertyUtils.getPropertyType(sockIOPool, key);
logger.debug("Type=" + type + ";Key=" + key + ";Value=" + value);
Object val = ConvertUtils.convert(value, type);
PropertyUtils.setSimpleProperty(sockIOPool, key, val);
} catch (IllegalAccessException e) {
throw new MemcachedException("Init Pool Fail", e);
} catch (InvocationTargetException e) {
throw new MemcachedException("Init Pool Fail", e);
} catch (NoSuchMethodException e) {
throw new MemcachedException("Init Pool Fail", e);
}
}
sockIOPool.initialize();
}

private Integer[] getWeight(List<MemcachedServer> weigths) {
Integer[] w = new Integer[weigths.size()];
for (int i = 0; i < weigths.size(); i++) {
w[i] = weigths.get(i).getWeight();
}
return w;
}

private String[] getServer(List<MemcachedServer> servers) {
String[] s = new String[servers.size()];
for (int i = 0; i < servers.size(); i++) {
MemcachedServer server = servers.get(i);
s[i] = server.getAddress() + ":" + server.getPort();
}
return s;
}


}




(5)MemcachedCli -- memcached操作客户端(只有set,get方法)

[java] view plaincopyprint?
01.import java.util.Date; 
02.import java.util.Iterator; 
03.import java.util.Map; 
04.import java.util.Set; 
05. 
06.import com.danga.MemCached.MemCachedClient; 
07. 
08.public class MemcachedCli { 
09.     
10.    private static MemcachedCli unique = new MemcachedCli(); 
11.     
12.    private MemcachedCli() { 
13.        init(); 
14.    } 
15.     
16.    public static MemcachedCli getInstance() { 
17.        return unique; 
18.    } 
19.     
20.    private MemCachedClient client = new MemCachedClient(); 
21.     
22.    private void init() { 
23.        client.setPrimitiveAsString(true); 
24.        client.setCompressEnable(true); 
25.        client.setCompressThreshold(4 * 1024); 
26.    } 
27.     
28.    public boolean set(String key, Object value) { 
29.        return client.set(key, value); 
30.    } 
31.     
32.    public boolean set(String key, Object value, Date expired) { 
33.        return client.set(key, value, expired); 
34.    } 
35.     
36.    public Object get(String key) { 
37.        return client.get(key); 
38.    } 
39.     
40.    public void printStat() { 
41.        Map stats = client.stats(); 
42.        Set keys = stats.keySet(); 
43.        Iterator keyIter = keys.iterator(); 
44.        while (keyIter.hasNext()) { 
45.            String key = (String)keyIter.next(); 
46.            Object value = stats.get(key); 
47.            System.out.println(key + "=" + value); 
48.        } 
49.    } 
50.     
51.} 
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.danga.MemCached.MemCachedClient;

public class MemcachedCli {

private static MemcachedCli unique = new MemcachedCli();

private MemcachedCli() {
init();
}

public static MemcachedCli getInstance() {
return unique;
}

private MemCachedClient client = new MemCachedClient();

private void init() {
client.setPrimitiveAsString(true);
client.setCompressEnable(true);
client.setCompressThreshold(4 * 1024);
}

public boolean set(String key, Object value) {
return client.set(key, value);
}

public boolean set(String key, Object value, Date expired) {
return client.set(key, value, expired);
}

public Object get(String key) {
return client.get(key);
}

public void printStat() {
Map stats = client.stats();
Set keys = stats.keySet();
Iterator keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = (String)keyIter.next();
Object value = stats.get(key);
System.out.println(key + "=" + value);
}
}

}




(6)MCTest -- 简单测试

[java] view plaincopyprint?
01.import java.util.ArrayList; 
02.import java.util.List; 
03. 
04.public class MCTest { 
05.     
06.    public static void main(String[] args) { 
07.        try { 
08.            MemcachedServer server = new MemcachedServer("localhost", 11211, 1); 
09.            List<MemcachedServer> servers = new ArrayList<MemcachedServer>(); 
10.            servers.add(server); 
11.            MemcachedPool pool = MemcachedPool.getInstance(); 
12.            pool.initPool(servers); 
13.            MemcachedCli client = MemcachedCli.getInstance(); 
14.            String value = (String)client.get("test1"); 
15.            System.out.println("value=" + value); 
16.            client.set("test1", "value1"); 
17.            value = (String)client.get("test1"); 
18.            System.out.println("value=" + value); 
19.            client.printStat(); 
20.        } catch (MemcachedException e) { 
21.            e.printStackTrace(); 
22.        } 
23.    } 
24.     
25.} 
import java.util.ArrayList;
import java.util.List;

public class MCTest {

public static void main(String[] args) {
try {
MemcachedServer server = new MemcachedServer("localhost", 11211, 1);
List<MemcachedServer> servers = new ArrayList<MemcachedServer>();
servers.add(server);
MemcachedPool pool = MemcachedPool.getInstance();
pool.initPool(servers);
MemcachedCli client = MemcachedCli.getInstance();
String value = (String)client.get("test1");
System.out.println("value=" + value);
client.set("test1", "value1");
value = (String)client.get("test1");
System.out.println("value=" + value);
client.printStat();
} catch (MemcachedException e) {
e.printStackTrace();
}
}

}



测试运行结果,其中有memcached client包的调试信息:



com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ retrieving object and stuffing into a string.
value=value1
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ storing data as a string for key: test1 for class: java.lang.String
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ memcache cmd (result code): set test1 0 0 6
(STORED)
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ data successfully stored for key: test1
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ retrieving object and stuffing into a string.
value=value1
localhost:11211={bytes_written=587, connection_structures=11, bytes=52, total_items=2, total_connections=21, uptime=284045336, pid=1416, get_hits=3, curr_items=1, version=1.2.1, cmd_get=4, time=1259425433, pointer_size=32, cmd_set=2, limit_maxbytes=67108864, bytes_read=162, curr_connections=10, get_misses=1}

分享到:
评论

相关推荐

    memcachedclient-2.0.1.jar

    memcachedclient-2.0.1.jar 之前在网上搜了很久没搜到,所以找到了跟大家分享

    Memcached-Java-Client-3.0.2.jar

    Memcached-Java-Client-3.0.2.jar

    Memcached-Java-Client-release_2.6.1.zip

    本文将围绕标题“Memcached-Java-Client-release_2.6.1.zip”展开,详细讲解如何在Java项目中整合并使用Memcached客户端库。 1. **Memcached简介** - Memcached是一种轻量级、基于内存的键值对存储系统,用于存储...

    Memcached-Java-Client-3.0.1.jar

    Memcached-Java-Client3.0.1

    cas-client-support-distributed-memcached-3.2.0.jar

    cas-client-support-distributed-memcached-3.2.0.jar

    memcached-client-php-0.1.2.rar_memcached-client_php_six4fu

    "memcached-client-php-0.1.2.rar" 是一个名为 "memcached-client-php" 的软件包的版本号为 "0.1.2" 的压缩文件,通常用于PHP环境中。"six4fu" 可能是开发者的别名或项目标识,表明这个版本是由这个人或团队编写的。...

    memcached-1.2.1-win32.zip 和 java_memcached-release_1.6.zip

    - 创建Memcached客户端实例,连接到服务器:`MemcachedClient client = new MemcachedClient(new InetSocketAddress("localhost", 11211));` - 存储数据:`client.set("key", 300, "value");` (300秒后过期) - ...

    memcached-client.php

    memcached-client.php

    memcached java client

    本篇文章将详细介绍两个常用的Java Memcached客户端:xmemcached和memcache-client-forjava。 **1. xmemcached** xmemcached是由Ketoo开发的一个高性能、高可用性的Java Memcached客户端。它提供了丰富的API,支持...

    memcached client for java

    memcached的java客户端jar包,方便调用memcached的服务

    Memcached1.4.4-14

    - 创建一个`MemcachedClient`实例,并设置服务器地址和端口。 ```csharp var client = new MemcachedClient(); client.Connect("127.0.0.1", 11211); ``` - 存储和检索数据: ```csharp client.Set("key", ...

    memcached for java client 例子

    "memcached for java client 例子" 指的是一个使用Java语言编写的客户端库,用于与memcached缓存系统进行交互。Memcached是一种高性能、分布式内存对象缓存系统,常用于减轻数据库负载,提升Web应用的响应速度。 **...

    java_memcached-release_2.5.1

    这次主要的优化工作还是在三个方面:应用服务器(Apache,JBoss)配置,业务流程,Cache Client包(http://code.google.com/p/memcache-client-forjava/ )。这里把过去和这次优化对于Cache的使用作一个经验分享,...

    python-memcached python-memcached

    1. **键值存储**:Python-memcached允许开发者使用键(key)和值(value)对来存储数据。键是唯一的标识符,而值可以是任何Python序列化支持的数据类型。 2. **多服务器支持**:你可以配置Python-memcached连接到多...

    memcached安装包以及MemCachedClient

    对于 Java 开发者,`MemCachedClient` 是一个常用的 Memcached 客户端库。这里我们关注的是 `java_memcached-release_2.6.6.jar` 文件,这是 Spymemcached 库的一个版本,它提供了与 Memcached 服务器通信的接口。 ...

    memcached-client

    memcached-client类,当没有权限配置php.ini时,可以用此来操作memcache

    Memcached-Java-Client-3.0.2.jar中文-英文对照文档.zip

    中文-英文对照文档,中英对照文档,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压 【***.jar中文文档.zip】,再解压其中的 【***-...

    memcaChed java client jar包

    MemcachedClient client = new MemcachedClient(new InetSocketAddress("localhost", 11211)); ``` 这里`localhost`是Memcached服务器的地址,`11211`是默认的Memcached端口号。 2. 存储数据: ```java client.set...

    java_memcached-release_2.6.3.zip

    MemcachedClient memcachedClient = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses("localhost:11211")); ``` 接着,可以使用`set`方法存储数据,`get`方法获取数据,`delete`方法...

Global site tag (gtag.js) - Google Analytics