Thursday, 19 May 2011

Generating Message and Correlation Identifiers

SOA messages often need to include, as part of their schema, some kind of unique identifier. This is usually called ‘message identifier’ or even ‘correlation identifier’. The idea here is that when a calling service receives a reply from your service, it’ll know what your service is talking about. This is especially helpful when the call is asynchronous.

One VERY useful class in the Java API that was introduced in Java 5 is UUID which stands for Universally Unique Identifier and is represented by a 128 bit value. You’ve probably seen various textual representations of a UUID, which generally look like this:

5d41402a-bc4b-3a76-b971-9d911017c592

The UUID class gives you several ways to generate a unique id, but the simplest one is:

    UUID uuid = UUID.randomUUID();

which will generate a UUID using a cryptographically strong pseudo random number generator.

To turn a string like the one above into an UUID object use:

    uuid = UUID.fromString(uuid.toString());

You can also generate one from your own set of bytes:

    uuid = UUID.nameUUIDFromBytes("my_string".getBytes());

or from a couple of random numbers:

    uuid = new UUID(1L, 128L);

If you're really interested in how UUID strings are generated, take a look at RFC 4122: A Universally Unique IDentifier (UUID).

No comments: