Micro services on the JVM part 1 – Clojure

Micro services could be a buzzword of 2014 for me. Few months ago I was curious to try Dropwizard framework as a separate backend, but didn’t get the whole idea yet. But then I watched a mind-blowing “Micro-Services Architecture” talk by Fred George. Also, the 4.0 release notes of Spring covers microservices as an important rising trend as well. After 10 years of having SOA in mind, but still developing monoliths, it’s a really tempting idea to try to decouple systems into a set of independently developed and deployed RESTful services. Micro services could be a buzzword of 2014 for me. Few months ago I was curious to try Dropwizard framework as a separate backend, but didn’t get the whole idea yet. But then I watched a mind-blowing “Micro-Services Architecture” talk by Fred George. Also, the 4.0 release notes of Spring covers microservices as an important rising trend as well. After 10 years of having SOA in mind, but still developing monoliths, it’s a really tempting idea to try to decouple systems into a set of independently developed and deployed RESTful services.

Micro services could be a buzzword of 2014 for me. Few months ago I was curious to try Dropwizard framework as a separate backend, but didn’t get the whole idea yet. But then I watched a mind-blowing “Micro-Services Architecture” talk by Fred George. Also, the 4.0 release notes of Spring covers microservices as an important rising trend as well. After 10 years of having SOA in mind, but still developing monoliths, it’s a really tempting idea to try to decouple systems into a set of independently developed and deployed RESTful services.

So when I decided to write a simple API for my DevRates.com website, instead of adding some code to existing codebase, I wanted to build a separate tiny app. But what’s the best stack for micro-services? In this series of posts I’ll try to compare various JVM technology stacks for this approach.

Here is my list of must-have features for the stack:

  • declarative REST support (no manual URL parsing)
  • native JSON support (bidirectional JSON-object mapping)
  • single “fat” jar packaging, no web container needed
  • fast development feedback loop (eg. runtime code reloading)
  • Swagger and Metrics integration

In this post I’ll try to cover Clojure with Ring and Compojure.

TL;DR

You can find all the covered concepts in the following GitHub examples:

Basic setup

There is an excellent Zaiste’s tutorial showing how to kickstart REST app with Compojure, just follow these few simple steps (the rest of the post assumes compojure-rest as the app name).

My sample route from handler.clj:

(defroutes app-routes (GET "/messages/:name" [name] {:body {:message (str "Hello World" " " name)}}) (route/resources "/") (route/not-found "Not Found"))

Fat jar

In a simple setup, Compojure app is being run through lein ring plugin. To enable running it as a standalone command-line app, you have to write a main method which starts Jetty server.

project.clj

:dependencies ... [ring/ring-jetty-adapter "1.2.0"] .. :main compojure-rest.handler

handler.clj

To build a single “fat” jar just run lein uberjar, and then java -jar target/compojure-rest-0.1.0-SNAPSHOT-standalone.jar runs the app.

(ns compojure-rest.handler ... (:require ... [ring.adapter.jetty :refer (run-jetty)]) (:gen-class)) ... (defn -main [& args] (run-jetty app {:port 3000 :join? false }))

Swagger

The nice thing about Compojure is that you can easy expose Swagger documentation by using swag library. There are some conflicts between swag and ring lein plugin, so just look at the compojure-swag for a working example.

Here is a typical snippet from handler.clj:

(set-base "http://localhost:3000") (defroutes- messages {:path "/messages" :description "Messages management"} (GET- "/messages/:name" [^:string name] {:nickname "getMessages" :summary "Get message"} {:body {:message (str "Hello World" " " name)}}) (route/resources "/") (route/not-found "Not Found"))

So, swag introduces defroutes-, GET-, POST- which take additional metadata as parameters to generate Swagger docs. If you’re little scared with this ^:string fragment – check metadata section from Clojure manual. Swagger-compatible definition should be available at http://localhost:3000/api-docs.json after running the app.

Metrics

To expose basic metrics of your REST API calls just use Ring-compatible metrics-clojure-ring library.

project.clj

:dependencies ... [metrics-clojure-ring "1.0.1"] ...

handler.clj

(ns compojure-rest.handler ... (:require ... [metrics.ring.expose :refer [expose-metrics-as-json]] [metrics.ring.instrument :refer [instrument]])) ... (def app (expose-metrics-as-json (instrument app) "/stats/"))

After generating some load by eg. wrk, you can check the collected stats by visiting http://localhost:3000/stats/.

ring.requests.rate.GET: { type: "meter", rates: { 1: 189.5836593065824, 5: 39.21602480726734, 15: 13.146759983907245 } }

Some random Clojure thoughts

  • The best newbie guide to Clojure is Kyle Kingsbury’s “Clojure from the ground up” series.
  • Leiningen is probably the best build tool for the JVM. Easy to install, fast, simple, no XML – just doing it right. And the “new” project templates is what’s Maven been missing from ages (anyone using archetypes?).
  • Lighttable is great! I’m really impressed with the fast feedback loop by just ctrl+entering the expressions.
  • Also, live reloading with ring server works fine. Just change the change code and see the changes immediately. Rapid!
  • Unlike other recently popular languages, Clojure has no killer-framework. Rails, Play/Akka, Grails/Gradle – all of these are key parts of Ruby, Scala and Groovy ecosystems. What about Clojure? A collection of small (micro?) libraries doing one thing well and working great together – just like Unix commands.
  • It may be true that Clojure is not good for large projects. With all the complex contructs (meta or ) and no control of the visibility, it could be hard to maintain large codebase. But it’s not a first-class problem in a micro-services world..

Resources

You May Also Like

JCE keystore and untrusted sites

Recently at work I was in need of connecting to a web service exposed via HTTPS. I've been doing this from inside Servicemix 3.3.1, which may seem a bit inhibiting, but that was a requirement. Nevertheless I've been trying my luck with the included ser...Recently at work I was in need of connecting to a web service exposed via HTTPS. I've been doing this from inside Servicemix 3.3.1, which may seem a bit inhibiting, but that was a requirement. Nevertheless I've been trying my luck with the included ser...

Log4j and MDC in Grails

Log4j provides very useful feature: MDC - mapped diagnostic context. It can be used to store data in context of current thread. It may sound scary a bit but idea is simple.

My post is based on post http://burtbeckwith.com/blog/?p=521 from Burt Beckwith's excellent blog, it's definitely worth checking if you are interested in Grails.

Short background story...


Suppose we want to do logging our brand new shopping system and we want to have in each log customer's shopping basket number. And our system can be used at once by many users who can perform many transactions, actions like adding items and so on. How can we achieve that? Of course we can add basket number in every place where we do some logging but this task would be boring and error-prone. 

Instead of this we can use MDC to store variable with basket number in map. 

In fact MDC can be treated as map of custom values for current thread that can be used by logger. 


How to do that with Grails?


Using MDC with Grails is quite simple. All we need to do is to create our own custom filter which works for given urls and puts our data in MDC.

Filters in Grails are classes in directory grails-app/conf/* which names end with *Filters.groovy postfix. We can create this class manually or use Grails command: 
grails create-filters info.rnowak.App.Basket

In result class named BasketFilters will be created in grails-app/conf/info/rnowak/UberApp.

Initially filter class looks a little bit empty:
class BasketFilters {
def filters = {
all(controller:'*', action:'*') {
before = {

}
after = { Map model ->

}
afterView = { Exception e ->

}
}
}
}
All we need to do is fill empty closures, modify filter properties and put some data into MDC.

all is the general name of our filter, as class BasketFilters (plural!) can contain many various filters. You can name it whatever you want, for this post let assume it will be named basketFilter

Another thing is change of filter parameters. According to official documentation (link) we can customize our filter in many ways. You can specify controller to be filtered, its actions, filtered urls and so on. In our example you can stay with default option where filter is applied to every action of every controller. If you are interested in filtering only some urls, use uri parameter with expression describing desired urls to be filtered.

Three closures that are already defined in template have their function and they are started in these conditions:

  • before - as name says, it is executed before filtered action takes place
  • after - similarly, it is called after the action
  • afterView - called after rendering of the actions view
Ok, so now we know what are these mysterious methods and when they are called. But what can be done within them? In official Grails docs (link again) under section 7.6.3 there is a list of properties that are available to use in filter.

With that knowledge, we can proceed to implementing filter.

Putting something into MDC in filter


What we want to do is quite easy: we want to retrieve basket number from parameters and put it into MDC in our filter:
class BasketFilters {
def filters = {
basketFilter(controller:'*', action:'*') {
before = {
MDC.put("basketNumber", params.basketNumber ?: "")
}
after = { Map model ->
MDC.remove("basketNumber")
}
}
}
}

We retrieve basket number from Grails params map and then we put in map under specified key ("basketNumber" in this case), which will be later used in logger conversion pattern. It is important to remove custom value after processing of action to avoid leaks.

So we are putting something into MDC. But how make use of it in logs?


We can refer to custom data in MDC in conversion patter using syntax: %X{key}, where key is our key we used in filter to put data, like:
def conversionPattern = "%d{yyyy-MM-dd HH:mm:ss} %-5p %t [%c{1}] %X{basketNumber} - %m%n"


And that's it :) We've put custom data in log4j MDC and successfully used it in logs to display interesting values.