gdx 发表于 2017-4-15 11:52:43

memcache simple practice in Java

Memcache is C/S structure, server is not supported on windows offical, but we can find one windows server here
install
here is the install guide on windows:
The win32 version of memcached can be run both as a NT Service or from the command line. To install memcached as a service, follow the next steps:
Unzip the binaries in your desired directory (eg. c:\memcached)
Install the service using the command: 'c:\memcached\memcached.exe -d install' from the command line
Start the server from the Microsoft Management Console or by running the following command: 'c:\memcached\memcached.exe -d start'
Use the server, by default listening to port 11211
Java client
Many clients are available for diferent lauguage, and more than one in java.
Here use memcache-java-client, which is more generic.alisoft is annother good choice.
maven dependency for Memcached-Java-Client.

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


here's my demo code

package com.lingceng.MemcacheDemo;
import com.whalin.MemCached.MemCachedClient;
import com.whalin.MemCached.SockIOPool;

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",
"127.0.0.1:11211"
};
//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 basic pool settings
// 5 initial, 5 min, and 250 max conns
// and set the max idle time for a conn
// to 6 hours
pool.setInitConn( 5 );
pool.setMinConn( 5 );
pool.setMaxConn( 250 );
pool.setMaxIdle( 1000 * 60 * 60 * 6 );
// set the sleep for the maint thread
// it will wake up every x seconds and
// maintain the pool size
pool.setMaintSleep( 30 );
// 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();

// lets set some compression on for the client
// compress anything larger than 64k
//mcc.setCompressEnable( true );
//mcc.setCompressThreshold( 64 * 1024 );
}
// from here on down, you can call any of the client calls
public static void main(String[] args) {
mcc.set( "foo", "This is a test String" );
String bar = (String) mcc.get( "foo" );
System.out.println(bar);
}
}


api or docs
memcached basic use
memcached java client howto
页: [1]
查看完整版本: memcache simple practice in Java