You might be curious what the simplest Java program to talk to Membase might look like, and how you might compile and run it using just the Java command line tools. Follow along if you like and look at Listing 1.
Listing 1: Main.java
import java.io.IOException; import java.util.concurrent.TimeUnit; import net.spy.memcached.AddrUtil; import net.spy.memcached.MemcachedClient; public class Main { public static void main(String[] args) { MemcachedClient client; try { client = new MemcachedClient(AddrUtil.getAddresses(args[0])); } catch (IOException e) { e.printStackTrace(); return; } Object spoon = client.get("spoon"); if (spoon == null) { System.out.println("There is no spoon."); client.set("spoon", 10, "Hello World!"); } else { System.out.println((String)spoon); } client.waitForQueues(1, TimeUnit.MINUTES); System.exit(0); } }
Enter the code in listing 1 into a file named Main.java
Place the downloaded spymemcached-2.6.jar file into the same directory.
Type the following commands:
$ javac -cp spymemcached-2.6.jar Main.java $ java -cp .:spymemcached-2.6.jar Main 10.0.0.33:11211
Of course, substitute your own Memcache server IP address. If you are on Linux or MacOS replace the semi-colon in the second command-line with a colon. The program will produce the following output:
2011-05-12 22:11:56.281 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=/10.0.0.33:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue 2011-05-12 22:11:56.284 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl @15dfd77 There is no spoon.
Much of this output is logging statements produced by the client library, to inform you of what's going on inside the client library to help you diagnose issues. It says that a connection to Membase was added and that the connection state changed. Then the code shows that the key spoon does not exist in Membase.
Running the program again, within 10 seconds will produce the following output:
2011-05-12 22:14:15.800 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=/10.0.0.33:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue 2011-05-12 22:14:15.803 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl @15dfd77 Hello World!
Again you see the log statements, followed by the indication that this time, the key spoon was found in Membase with the value "Hello World!" Congratulations, you've taken your first small step into a much larger world.