High performance

XMemcached Introduction

XMemcached is a new java memcached client. Maybe you don't know "memcached" so far,you can check . It is a free & open source,high-performance,distributed memory object caching system,generic in nature,but intended for use in speeding up dynamic web applications by alleviating database load. And many users use it as memory database too. Memcached talk with client with self define protocol,XMemcached is a java client for it.

There are two java clients before: the official client base on traditional blocked IO,maintained by ,the  based on java NIO,maintained by Dustin Sallings. And there are some improved version base on them too. So,what's advantage of XMemcached,why we need a new java client for Memcached?

XMemcached Features

High performance

XMemcached is a client which base on java NIO too,Java NIO is efficient (special under high concurrent),and use less resource than traditional blocked IO. The traditional blocked IO need create some connections to build a connection pool for improve efficiency. But NIO only need one connection (sure,NIO also support pool management),reduce the cost for thread creation and switch,it is more obvious under hight concurrent. So the performance of XMemcached and Spymemcached are very excellent,and in some point,XMemcached is more excellent than Spymemcached,you can check  for details.

Binary and Text protocol

XMemcached support all protocols of memcached,also included  from Memcached 1.4.0.

Client distribution

Memcached supports distribution by client,and XMemcached implements it,and supply implement of consistent hash algorithm.

Weighted server

XMemcached can adjust weight of node for balance the load of memcached server,the weight is more high,the memcached server will store more data,and receive more load.

Dynamically add/remove server

XMemcached can dynamically add/remove server,by JMX or programming,it is easy to extend server or replace server.

JMX Monitor/Control

You can monitor or control XMemcached client by JMX,you can set some parameters,view the STAT. data,add or remove server etc.

Integration with Spring and Hibernate-memcached

Just like many projects,XMemcached also support integration with Spring framework.  is a open source project,it can use memcached as secondary cache of hibernate,the default is Spymemcached,you can use XMemcached too.

NIO Connection Pool

As mentioned before,Java NIO will use one connection for one memcached server at most time,but XMemcached can also support connection pool. You can create a few connections to build a connection pool to one memcached server,it can improve the performance under high concurrent environment,and it is transparent to user. You must assure the data's independence or synchronization of data,there is no synchronization between connections to a server,you must make sure the data are all independent,or you can use CAS for atomic operation.

Expendable

XMemcached is implemented under java NIO framework,with clear architecture. (yanf4j is combined into XMemcached after XMemcached 1.2.5). You can find the classes UML diagram of XMemcached here

User Guide

We will show you some examples from simple to complex,then you can learn XMemcached easily.

Dependence

XMemcached depend on

You must download dependence or download whole XMemcached package with dependence before test following code.

If you use maven

If you build your project with maven,you can only add dependency to use XMemcached (only for 1.2.5+)

Simple Example

As the general user,you need to add/get data from memcached at most time. If we have a memcached server,the IP address or host name is "host",the service port is 11211,you can check this simple example:

Note: For save time,please import packages by yourself or by IDE.

Since XMemcachedClient has many options to create,there is a XMemcachedClientBuilder class to help build MemcachedClient. The MemcachedClient is a main interface,you can find almost methods in this class. XMemcachedClient is a implement of MemcachedClient.

When you use XMemcachedClientBuilder,the parameter of memcached server list should be a string which just like "host1:port1 host2:port2 …" ,the AddrUtil.getAddresses will get IP addresses list after parse it.

You can use "set" to store data,it has 3 parameters,the first is key name,the second is expire time (second),after the expire time,you can't find the key in memcached server. The third parameter is the data for store,it can be any java serialized object.

You can use "get" with a key name for retrieve data. If you will remove stored data,you can use "delete" with a key.

Since XMemcached is based on NIO,so the process of communication is asynchronous,When the client send a request to memcached server,you can't know how long you will receive the response,client can only wait,so there is a concept of timeout. After send a request,the client will regard it is failed after some time if no response. The default timeout value is 5 second(since 1.3.8,before is 1 second). The above example use default timeout time for all calls. If you need different timeout,you can use like this:

It will timeout after 3 seconds,you will get a TimeoutException if no response in 3 second,you need handle the exception by your code. And you need handle InterruptException too,because the method use CountDownLatch.await(timeout) internally. And if MemcachedException occurred,it means some exceptions in XMemcached internal,just like encode/decode exception,or network failed.

touch and getAndTouch

Memcached 1.4 supports touch protocol to update cache item's expire time using key without value. Xmemcached 1.3.6 supports binary touch and getAndTouch commands,and xmemcached 1.3.8 supports text touch command:

Client distribution

The distribution of Memcached is implement by client side,Client will get a memcached server by hash of key,then store the value to the server.

XMemcached support client distribution strategy,the default strategy is Standard Hash: "hash(key) mod server_count",you need do nothing if use default strategy.

XMemcached also support ,it need set by method:

You can check "Integration with Spring Framework" for configuration.

XMemcached supply another hash algorithm -- Election Hash,you can use it in some case,just like:

CAS Operation

Memcached implement atomic update by CAS protocol,actually it is compare and set,the theory like Optimistic locking,it will bring a cas value when request to store a data,memcached will check the cas value with current cas value,it will overwrite old data if the value is same,otherwise it failed. It is very useful in concurrent environment. XMemcached support CAS protocol,whatever text protocol or binary protocol. CAS protocol has two steps: get CAS value and try update,so a typical use case should like:

First you can get a GetsResponse by "gets" method,this object include the stored data and cas value,then try to update the value by "cas" method,it will print "cas error" if failed. Obvious,it is a little complicated. If you will try many atomic update you need a loop,so XMemcached supply a CASOperation interface to implement it,it allows you try N times to atomic update the data of the key,you don't need get cas value by call "gets" again,just like this:

()

CASOperation interface only has two method,one method "getMaxTries" is used to set max try times,it is 1 time by default,if bigger than "Max Tries",it will throw a TimeoutException,if you will try more times,just set a big value; another method is "getNewValue",the returned value will be stored if not failed,the parameters of this method are get from last GetsResponse result by call "gets".

More Examples

Here is more example,show how to call methods of MemcachedClient:

First it store a "world" value by "hello" key,and call "add" and "replace",since the key exists,so "add" will failed,at same situation,"replace" will be ok,the value is updated to "dennis" from "world". Then we call append and prepend,append a " good" for the value,and insert "hello " before the value,then we can get the last value is "hello dennis good". And we call "deleteWithNoReply" to remove the data,this method will remove data and memcached will return nothing,so this method don't need wait the response,it is very good for batch operation. You will find xxxWithNoReply version for set/add/replace,please check API document for details.

Iterate all keys

Memcached is not supply a method to iterate all keys,but you can iterate all key by "stats items" and "stats cachedump" protocol,but is low performance,it is not recommended. XMemcached only support iterate in text protocol now.

If you want iterate all keys,you need retrieve a KeyIterator:

Incr/Decr

The following code show you how to use incr/decr,these two operations are like AtomicInteger class in java,for increase and decrease atomically:

"incr" and "decr" both have method with 3 parameters,the first is the key name,the second is step,the third is default value if key is not exist. and them have method with 2 parameters too,the third parameter is removed,it will use "0" as default value.

XMemcached also supply a Counter class,it packing the incr/decr method,you can use it just like AtomicInteger:

The second parameter is for initial value for counter.

Namespace APIs

Since 1.4.2,xmemcached supports namespace pattern in memcached,you can put a group of items into a namespace in memcached,and invalidate a group of cache item at one time,for example:

()()

STAT. Information

Memcached supply protocol for view stat. information.

>

getStats method will return a map,it stored all stat. data of all active memcached servers,you can stat special data,e.g. "items":

>

You only need set the parameter value by the name (items,sizes,slabs).

SASL authentication

Memcached 1.4.3 start to support client SASL authentication,after enable SASL in server side,client need authentication with server,otherwise will be denied. XMemcached support this feature since 1.2.5. Assume memcached server enable the SASL authentication,use "cacheuser" as user name,use "123456" as password,you need access Memcached like this:

Note: SASL authentication only support binary protocol.

If you will use Spring configuration,please check "Integration with Spring Framework" chapter.

Advance Topic

Integration with Spring Framework

You can use XMemcachedClientFactoryBean class,it can work with Spring,just like:

Then you can use the bean when you need it.

The following is more configuration in Spring Configuration File,include protocol,consistent hash,weighted server,connection pool,even included SASL authentication (Since XMemcached 1.2.5).

Parameters List:

<table class="wikitable">
<tr>
<td>Property Name</td>
<td>Value</td>
</tr>
<tr>
<td>servers</td>
<td>Memcached Server List: host1:port1 host2:port2</td>
</tr>
<tr>
<td>weights</td>
<td>Weight of servers,more high weight,more connections</td>
</tr>
<tr>
<td>authInfoMap</td>
<td>authentication information,only avaiable for XMemcached 1.2.5+</td>
</tr>
<tr>
<td>connectionPoolSize</td>
<td>NIO connection pool size,default 1</td>
</tr>
<tr>
<td>commandFactory</td>
<td>protocol factory,net.rubyeye.xmemcached.command.BinaryCommandFactory,TextCommandFactory (default),KestrelCommandFactory</td>
</tr>
<tr>
<td>sessionLocator</td>
<td>distributed strategy,consitent hash: net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator or ArraySessionLocator(default)</td>
</tr>

<table class="wikitable">
<tr>
<td>transcoder</td>
<td>serlize transcoder,use net.rubyeye.xmemcached.transcoders.SerializingTranscoder by default,more details please checkjavadoc</td>
</tr>
<tr>
<td>bufferAllocator</td>
<td>IoBuffer allocator,use net.rubyeye.xmemcached.buffer.SimpleBufferAllocator by default,also support CachedBufferAllocator(not recommended now)</td>
</tr>

Spring 3.0 and Builder Configuration

Spring 3.0 use a different way to find "destroy" method,so if you just use above configuration,you will got a exception when start,the message will this: "Couldn't find a destroy method named 'shutdown' on bean",then XMemcached can't work in such situation,and Spring IOC container can't start too. Any solution? sure,you can create MemcachedClient by factory method in XmemcachedClientBuilder,here is a example:

Weighted Server

If you use spring,please check above chapter. If you will set it by programming,here it is:

It passes into an int array,the value is for the weight of server,so you can see the weight is 1 for "localhost:12000" server,and the weight is 3 for "localhost:12001" server. And you should know the weight of XMemcached is implement by connection counte,you will find 3 connections if the weight is 3,MemcachedSessionLocator will find them in connection session list.

You can update the weight for one server,use setServerWeight:

Use binary protocol

If you use spring,please check "Integration with Spring Framework" chapter.

Memcached support binary protocol from version 1.4,XMemcached support binary protocol from version 1.2. It is simple to enable this feature,just set CommandFactory:

The default protocol use TextCommandFactory for Text Protocol.

JMX Support

You can monitor XMemcached by JMX,you need add some options when you start jvm:

XMemcached exposes service by RMI:

And you can check these MBean by jconsole.

It includes following MBeans:

More JMX Options:

Dynamically add/remove server

You can use JMX to do it,or by programming:

NIO Connection Pool

XMemcached is base on java NIO,it has one connection to one Memcached server by default,it is very excellent in most projects. But in some typical high-concurrent enviornment,it will has bottleneck too. So Xmemcached support NIO connection pool,it can create multiple connections to one Memcached server. But you should know,they are not synchronized,so you must make sure the synchronzation of data update. You can enable connection pool with following code:

If you use spring,please check "Integration with Spring Framework" chapter.

Talk with Kestrel

Kestrel is a open source project by twitter by scala language,it is a simple and high-performance MQ. It support Memcached text protocol,but not full compatibled,e.g. it can't support flag,so many client can't work since they use flag for serlization. XMemcached support a KestrelCommandFactory to support Kestrel. With KestrelCommandFactory you can:

  • close get with multiple keys,because Kestrel doesn't support bulk get.
  • support Blocking Fetch and Reliable Fetch of Kestrel.
  • support store any java serializable type.

Use KestrelCommandFactory like this:

You should note,since Kestrel doesn't support flag,so XMemcached append 4 bytes as flag before stored data,if all your application use XMemcached,it is fine,but if you will use other client,maybe it will not work again,so you can turn of this feature by:

After set it to true,all the primitive type will be stored as string,but you can' store serializable type now.

Talk with tokyotyrant

You can talk with TokyoTyrant by TokyoTyrantTranscoder,but TokyoTyrant doesn't support flag/exptime in memcached text protocol,so TokyoTyrantTranscoder append 4 bytes before value as flag,maybe it will not compatibled,just like talk with Kestrel.

Integration with Hibernate-memcached

Like use spymemcahed,you can check wiki of hibernate-memcached,if use XMemcached,first you need set memcacheClientFactory to XmemcachedClientFactory.

<table class="wikitable">


<tr>
<td>Property</td>
<td>Value</td>
</tr>
<tr>
<td>hibernate.memcached.memcacheClientFactory</td>
<td>net.rubyeye.xmemcached.utils.hibernate.XmemcachedClientFactory</td>
</tr>

And please note other properties,they have many difference:

<table class="wikitable">


<tr>
<td>Property</td>
<td>Value</td>
</tr>
<tr>
<td>hibernate.memcached.servers</td>
<td>localhost:11211 localhost:11212</td>
</tr>
<tr>
<td>ibernate.memcached.cacheTimeSeconds</td>
<td>300</td>
</tr>
<tr>
<td>hibernate.memcached.keyStrategy</td>
<td>HashCodeKeyStrategy</td>
</tr>
<tr>
<td>hibernate.memcached.readBufferSize</td>
<td>DEFAULT_SESSION_READ_BUFF_SIZE</td>
</tr>
<tr>
<td>hibernate.memcached.operationTimeout</td>
<td>DEFAULT_OP_TIMEOUT</td>
</tr>
<tr>
<td>hibernate.memcached.hashAlgorithm</td>
<td>NATIVE_HASH,KETAMA_HASH etc.</td>
</tr>
<tr>
<td>hibernate.memcached.commandFactory</td>
<td>TextCommandFactory,BinaryCommandFactory</td>
</tr>
<tr>
<td>hiberante.memcached.sessionLocator</td>
<td>ArrayMemcachedSessionLocator,KetamaMemcachedSessionLocator</td>
</tr>

Compression、sanitizeKeys and misc.

Data compression

Memcached is inefficient when you store large data,XMemcached will help you compress large data,and auto uncompress and deserilize data when you retrieve the data,the Threshold is 16K by default,you can set the threshold by setCompressionThreshold in Transcoder interface,you can set it to 1K:

This method is introduced since version 1.2.1,you can do it by this before version 1.2.1:

packZeros

There is a special process when XMemcached serialize number type,There prefix zeors will be removed,the data will more smaller. For example the number "3" will be serialized into "0x0003",it will convert into "0x3" after process. And it will append zeros when deserialization by the number type automaticlly. The feature is turned on by default,you can turn it off for compatibility.

sanitizeKeys

There is a "sanitizeKeys" option in offical client,when you use URL as the key,MemcachedClient will encode the URL before store. It is off by default,you can enable it by:

This feature is introducted since version 1.2.1.

https://code.google.com/p/xmemcached/wiki/User_Guide#Changes_History

相关文章

文章浏览阅读1.3k次。在 Redis 中,键(Keys)是非常重要的概...
文章浏览阅读3.3k次,点赞44次,收藏88次。本篇是对单节点的...
文章浏览阅读8.4k次,点赞8次,收藏18次。Spring Boot 整合R...
文章浏览阅读978次,点赞25次,收藏21次。在Centos上安装Red...
文章浏览阅读1.2k次,点赞21次,收藏22次。Docker-Compose部...
文章浏览阅读2.2k次,点赞59次,收藏38次。合理的JedisPool资...