Today we will look into Memcached Java client example. Earlier we learned about telnet commands for memcached with sample execution terminal logs. But most of the times we want to connect to the Memcached server through some other programming languages, such as Java and PHP.
Table of Contents
Memcached Java Clients
There are three most widely used memcached Java client API.
- xmemcached
- spymemcached
- gwhalin memcached client
Memcached Java Example
I have used Greg Whalin Memcached client and found it easy to understand and use. It provides all the basic functionalities with thread pooling. Below is the maven dependency to include this into your project.
<dependency>
<groupId>com.whalin</groupId>
<artifactId>Memcached-Java-Client</artifactId>
<version>3.0.2</version>
</dependency>
To help you get started quickly, I am providing a sample program to showcase the usage of basic functions that can be performed with the Memcached server.
package com.journaldev.memcached.test;
import java.util.HashMap;
import com.whalin.MemCached.MemCachedClient;
import com.whalin.MemCached.SockIOPool;
public class MemcachedJavaClient {
/**
* MemcachedJavaClient program to show the usage of different functions
* that can be performed on Memcached server with Java Client
* @param args
*/
public static void main(String[] args) {
//initialize the SockIOPool that maintains the Memcached Server Connection Pool
String[] servers = {"localhost:11111"};
SockIOPool pool = SockIOPool.getInstance("Test1");
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();
//Get the Memcached Client from SockIOPool named Test1
MemCachedClient mcc = new MemCachedClient("Test1");
//add some value in cache
System.out.println("add status: "+mcc.add("1", "Original"));
//Get value from cache
System.out.println("Get from Cache: "+mcc.get("1"));
System.out.println("add status: "+mcc.add("1", "Modified"));
System.out.println("Get from Cache: "+mcc.get("1"));
//use set function to add/update value, use replace to update and not add
System.out.println("set status: "+mcc.set("1","Modified"));
System.out.println("Get from Cache after set: "+mcc.get("1"));
//use delete function to delete the key from cache
System.out.println("remove status: "+mcc.delete("1"));
System.out.println("Get from Cache after delete: "+mcc.get("1"));
//Use getMulti function to retrieve multiple keys values in one function
// Its helpful in reducing network calls to 1
mcc.set("2", "2");
mcc.set("3", "3");
mcc.set("4", "4");
mcc.set("5", "5");
String [] keys = {"1", "2","3","INVALID","5"};
HashMap<String,Object> hm = (HashMap<String, Object>) mcc.getMulti(keys);
for(String key : hm.keySet()){
System.out.println("KEY: "+key+" VALUE: "+hm.get(key));
}
}
}
The output of the above Memcache java client program is:
add status: true
Get from Cache: Original
add status: false
Get from Cache: Original
set status: true
Get from Cache after set: Modified
remove status: true
Get from Cache after delete: null
KEY: 3 VALUE: 3
KEY: 2 VALUE: 2
KEY: 1 VALUE: null
KEY: INVALID VALUE: null
KEY: 5 VALUE: 5
If you want to connect to multiple Memcached servers then you will have to create multiple SockIOPool
instances and then use the same name while getting the MemcacheClient
instance.
Im using spring boot with apache camel and I have a class A where I set (add or update) a cached variable and in another class B I’m calling it using “get” but it retrieves nothing. I have to restart the server to get the cached valued refreshed. What I have to do to get it work in the first run.
Why Java memcached does not support multi key delete action?
Hi Pankaj,
I have some queries regarding key value expiration, please help me.
1. Is there any automatic expiration of key from memcache?
2. What is the default expiration-time for key in memcache?
3. When i stop memcache server and restarted, what is the liability of already stored key values in memcache? Can I able to get those key values from memcache?
Kindly clarify the above points please, Thanks for your support from your previous posts.
Kind Regards,
Ravi
Thanks mate, cann’t find any other example on the internet nor the official website.. painful.
Thanks!
Hi Pankaj,
I am working on windows environment could you please help me, how to install memcached server on Windows operating system
Kind Regards,
Ravi
Any Example Memcache spymemcache.jar because i have to used internet reffer example AddrUtil Class not identify in my project
btw are those Pool property settings necessary ?
Very helpful post. simple and clean
Thank you
Hi, Thanks for nice article.
I used the same example on windows machine and its able to read write values in cache on same server.
But when i am trying to connect to two memcached server, its not able to connect to other windows machine.
I have used same code as you mentioned, i only changes the server as below:-
String[] servers = { “localhost:11211”, “server2IP:11211” };
But it still accessing only local cache.
I ran same apps on other server and i am not able to get the value which i set from first server.
Also, i am getting the below error:-
63 [main] DEBUG com.meetup.memcached.SockIOPool – ++++ added server2IP:11211 to server bucket
63 [main] DEBUG com.meetup.memcached.SockIOPool – +++ creating initial connections (1) for host: server2IP:11211
3063 [main] ERROR com.meetup.memcached.SockIOPool – ++++ failed to get SockIO obj for: server2IP:11211
3063 [main] ERROR com.meetup.memcached.SockIOPool –
java.net.SocketTimeoutException
at sun.nio.ch.SocketAdaptor.connect(Unknown Source)
at com.meetup.memcached.SockIOPool$SockIO.getSocket(SockIOPool.java:1610)
at com.meetup.memcached.SockIOPool$SockIO.(SockIOPool.java:1583)
at com.meetup.memcached.SockIOPool.createSocket(SockIOPool.java:780)
at com.meetup.memcached.SockIOPool.populateBuckets(SockIOPool.java:669)
at com.meetup.memcached.SockIOPool.initialize(SockIOPool.java:632)
at com.meetup.memcached.test.TestMemcached.main(TestMemcached.java:39)
3079 [main] DEBUG com.meetup.memcached.SockIOPool – ++++ ignoring dead host: server2IP:11211 for 1000 ms
3079 [main] ERROR com.meetup.memcached.SockIOPool – ++++ failed to create connection to: server2IP:11211 — only 0 created.
Am i doing something wrong?
Please help me to resolve this.
Thanks in advance!
Regards
Archana
Dear Archana,
Try first with Telnet command to check whether you are able to access the other memcache server or not. I believe the other machine is under some firewall and that’s why connection is getting refused.
I have worked on Unix/Linux servers and it works fine.
Hi Pankaj,
I have tried same thing but i am getting below result please help me.
log4j:WARN No appenders could be found for logger (com.meetup.memcached.SockIOPool).
log4j:WARN Please initialize the log4j system properly.
add status:false
Get from Cache:null
add status:false
Get from Cache:null
set status:false
Get from Cache after set:null
remove status:false
Get from Cache after delete:null
KEY:2 VALUE:null
KEY:3 VALUE:null
KEY:5 VALUE:null
KEY:INVALID VALUE:null
KEY:1 VALUE:null
my client program is:
package com.meetup.memcached.test;
/**
* Created with IntelliJ IDEA.
* User: ravi
* Date: 27/2/14
* Time: 11:30 AM
* To change this template use File | Settings | File Templates.
*/
import java.util.HashMap;
import com.meetup.memcached.MemcachedClient;
import com.meetup.memcached.SockIOPool;
public class MemcachedJavaClient {
/**
* MemcachedJavaClient program to show the usage of different functions
* that can be performed on Memcached server with Java Client
* @param args
*/
public static void main(String[] args) {
//initialize the SockIOPool that maintains the Memcached Server Connection Pool
String[] servers = {“localhost:11211”};
SockIOPool pool = SockIOPool.getInstance(“test”);
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();
//Get the Memcached Client from SockIOPool named Test1
MemcachedClient mcc = new MemcachedClient(“test”);
//add some value in cache
System.out.println(“add status:”+mcc.add(“1”, “Original”));
//Get value from cache
System.out.println(“Get from Cache:”+mcc.get(“1”));
System.out.println(“add status:”+mcc.add(“1”, “Modified”));
System.out.println(“Get from Cache:”+mcc.get(“1”));
//use set function to add/update value, use replace to update and not add
System.out.println(“set status:”+mcc.set(“1″,”Modified”));
System.out.println(“Get from Cache after set:”+mcc.get(“1”));
//use delete function to delete key from cache
System.out.println(“remove status:”+mcc.delete(“1”));
System.out.println(“Get from Cache after delete:”+mcc.get(“1”));
//Use getMulti function to retrieve multiple keys values in one function
// Its helpful in reducing network calls to 1
mcc.set(“2”, “2”);
mcc.set(“3”, “3”);
mcc.set(“4”, “4”);
mcc.set(“5”, “5”);
String [] keys = {“1”, “2”,”3″,”INVALID”,”5″};
HashMap hm = (HashMap) mcc.getMulti(keys);
for(String key : hm.keySet()){
System.out.println(“KEY:”+key+” VALUE:”+hm.get(key));
}
}
}
is ur memcached server running fine, can you connect via telnet and run some commands?
did same thing it was able to connect.
could you please tell me the steps, how to make memcached server, i have down loaded Memcached-Java-Client-master.zip file in my local system and loaded in intelliJ IDE and testing through IDE
Hi Pankaj,
I am working on windows environment could you please help me, how to install memcached server on Windows operating system
Kind Regards,
Ravi
Please check https://www.journaldev.com/42/how-to-install-memcached-server-on-windows-as-service
Hi Pankaj,
I have some queries regarding key value expiration, please help me.
1. Is there any automatic expiration of key from memcache?
2. What is the default expiration-time for key in memcache?
3. When i stop memcache server and restarted, what is the liability of already stored key values in memcache? Can I able to get those key values from memcache?
Kindly clarify the above points please, Thanks for your support from your previous posts.
Kind Regards,
Ravi
Hi Pankaj,
Memcached for object storage. Default is 64MB, i want to increase the size, how can i proceed for this, how to increase this size in windows based memcache server?
Kind Regards,
Ravi.