The API contains methods that are able to atomically increment a variable in the database and decrement a variable. Effectively this means that these operations are safe for use by any client across the cluster at any time and there is some guarantee that these will be done in the right order. We will demonstrate these methods by tracking the total number of chat clients connected to the server.
Add the following lines to the run() method
after the connect method:
connect(serverAddress); register(); unregister(); client.shutdown(1, TimeUnit.MINUTES);
Then add the following two methods to the end of the class:
private boolean register() throws Exception { userId = client.incr("UserId", 1, 1); System.out.println("You are user "+userId+"."); userCount = client.incr("UserCount", 1, 1); System.out.println("There are currently "+userCount+" connected."); return true; } private void unregister() throws Exception { client.decr("UserCount", 1); System.out.println("Unregistered."); }
These two methods demonstrate the use of the
incr and decr methods, which
increment and decrement a variable, respectively. The application
you are building uses this to keep track of how many users are
currently running the program. This particular overload of the
incr method takes a default value that it will use if the key
UserCount does not exist, and will return the current count. In
this case the first user will be assigned user number 1. Finally,
when the unregister method is called, the decr method will be
called to subtract 1 from the UserCount value.
Finally, you must add the following member variables to the top of the class:
private long userId = 0; private long userCount = 0;
If you compile and run this program now, you will see the following output:
$ mvn assembly:assembly $ java -jar target\membasetutorial-exe.jar ... You are user 1. There are currently 0 connected. Unregistered. 15-May-2011 9:07:39 PM net.spy.memcached.MemcachedClient run INFO: Shut down memcached client
Up to this point, the application is doing some very simple things, allowing a user to connect, and keeping track of how many users and currently connected. It's time to start adding some data to the database, and providing some methods to interact between multiple clients.