Development, testing, ideas

Thursday, March 18, 2010

Async Twitting from Google App Engine

It's pretty nice to have some real-time monitoring info of what's happening in your app. Twitter and Task Queues can help to introduce non-intrusive, flexible and easy-to-to implement real-time monitoring.

  1. Put Twitter4J library jar to your app's WEB-INF/lib folder.
  2. In the place you want to monitor, add the following code that will schedule async twitter servlet call (assuming there's some entity that represents event we plan to publish):
    QueueFactory.getDefaultQueue().add(url("/twit").
    param("key", KeyFactory.keyToString(entity.getKey())));
  3. Create simple servlet, map it to handle /twit requests, and put the follwing code inside its doPostMethod:
    Twitter twitter = new TwitterFactory().getInstance("login", "pass");
    String keyString = req.getParameter("key");
    Key key = KeyFactory.stringToKey(keyString);
    String twit = buildTwitString(key);
    twitter.updateStatus(twit);
That's it!
Note. Don't forget to protect your twit servlet. You may want also use task request headers to handle reties.

Note 2. In the first code snippet, url method is static-imported from com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;

No comments:

About Me

My photo
Kharkov, Ukraine
Trying to find inspiration in work