---
title: "Memcached-Java-Client 使用"
author: "cjj_720"
date: "2010-08-05T16:04:15Z"
tags: []
categories: ["编程语言"]
slug: "memcached-java-client"
draft: false
lastmod: "2010-08-05T16:04:15Z"
id: 729917
url: "https://cprime.iteye.com/blog/729917"
---

假设有三台server，Server 1 和 server 2有3GB内存，server 3有2GB 内存空间用于缓存，
```java

import com.danga.MemCached.*;
public class MyClass {

	// create a static client as most installs only need
	// a single instance
	protected static MemCachedClient mcc = new MemCachedClient();

	// set up connection pool once at class load
	static {

		// server list and weights
		String[] servers =
			{
			  "server1.mydomain.com:1624",
			  "server2.mydomain.com:1624",
			  "server3.mydomain.com:1624"
			};

		Integer[] weights = { 3, 3, 2 };

		// grab an instance of our connection pool
		SockIOPool pool = SockIOPool.getInstance();

		// set the servers and the weights
		pool.setServers( servers );
		pool.setWeights( weights );

		// set some TCP settings
		// disable nagle
		// set the read timeout to 3 secs
		// and don't set a connect timeout
		pool.setNagle( false );
		pool.setSocketTO( 3000 );
		pool.setSocketConnectTO( 0 );

		// initialize the connection pool
		pool.initialize();
	}

        // from here on down, you can call any of the client calls
	public static void examples() {
        mcc.set( "foo", "This is a test String" );
		String bar = mcc.get( "foo" ).toString();
	}

```


如果想支持多种客户端 (i.e. Java, PHP, Perl, etc.)
需要如下设置

```java

	// use a compatible hashing algorithm
	pool.setHashingAlg( SockIOPool.NEW_COMPAT_HASH );

```