Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE. Founder and creator of http://computoser.com and http://welshare.com . Worked on Ericsson projects, Bulgarian e-government projects and large scale recruitment platforms. Member of the jury of the International Olympiad in Linguistics and the Program committee of the North American Computational Linguistics Olympiad. Bozhidar is a DZone MVB and is not an employee of DZone and has posted 82 posts at DZone. You can read more from them at their website. View Full User Profile

Replacing a JSON Message Converter With MessagePack

04.25.2012
| 3819 views |
  • submit to reddit

You may be using JSON to transfer data (we were using it in our message queue). While this is good, it has the only benefit of being human-readable. If you don’t care about readability, you’d probably want to use a more efficient serialization mechanism. Multiple options exist: protobuf, MessagePack, protostuff, java serialization. The easiest of them to use is java serialization, but it is less efficient (with both memory and time) than the other solutions. There are some benchmarks that will help you choose the most efficient solution, but if you want it to be easy and almost drop-in replacement to your JSON solution, MessagePack might be the best option.

I made a simple test to compare the JSON output to the MessagePack output in terms of size: 2300 vs 150 bytes for a simple message. Pretty good reduction, and if the messages are a lot, it’s a must to optimize.

However, you need to register all classes in the message pack. There are two options:

  • use @Message on all the objects in the serialized graph. This is a bit tedious, especially if you already have a lot of classes that are transferred. You have to go through the whole graph
  • you can manually register all classes with the mesagpack. Again tedious, because you also have to register all classes that the message class contains as a field (recursively)

That’s why I wrote the following code to loop all our message classes, and register them with the message pack on startup. It partly relies on spring classes, but if you are not using Spring, you can replace them:

   private MessagePack serializer = new MessagePack();
private ClassMapper classMapper = new DefaultClassMapper();

@PostConstruct
public void init() {
	// we need to find all messages, and register their classes, and also all their fields' recursively
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	Set<BeanDefinition> classes = provider.findCandidateComponents("com.foo.bar.messages");

               // hacking MessagePack to allow Set handling
	Field fld = ReflectionUtils.findField(MessagePack.class, "registry");
	ReflectionUtils.makeAccessible(fld);
	TemplateRegistry registry = (TemplateRegistry) ReflectionUtils.getField(fld, serializer);
	registry.register(Set.class, new SetTemplate(new AnyTemplate(registry)));
	registry.registerGeneric(Set.class, new GenericCollectionTemplate(registry, SetTemplate.class));

	try {
		for (BeanDefinition def : classes) {
			Class<?> clazz = Class.forName(def.getBeanClassName());
			registerHierarcy(clazz, serializer, Sets.<Class<?>>newHashSet());
		}
	} catch (ClassNotFoundException e) {
		throw new IllegalStateException(e);
	}
}

private void registerHierarcy(Class<?> clazz, MessagePack serializer, Set<Class<?>> handledClasses) {
	if (!isEligibleForRegistration(clazz)) {
		return;
	}
	Class<?> currentClass = clazz;
	while (currentClass != null && !currentClass.isEnum() && currentClass != Object.class) {
		for (Field field : currentClass.getDeclaredFields()) {
			registerHierarcy(field.getType(), serializer, handledClasses);

			// type parameters
			Type type = field.getGenericType();
			if (type instanceof ParameterizedType) {
				for (Type typeParam : ((ParameterizedType) type).getActualTypeArguments()) {
					// avoid circular generics references, resulting in stackoverflow
					Class<?> typeParamClass = (Class<?>) typeParam;
					if (!handledClasses.contains(typeParamClass)) {
						handledClasses.add(typeParamClass);
						registerHierarcy(typeParamClass, serializer, handledClasses);
					}
				}
			}
		}
		currentClass = currentClass.getSuperclass();
	}

	try {
		serializer.register(clazz);
	} catch (Exception ex) {
		logger.warn("Problem registering class " + clazz, ex.getMessage());
	}
}

private boolean isEligibleForRegistration(Class<?> clazz) {
	return !(clazz.isAnnotationPresent(Entity.class) || clazz == Class.class || Type.class.isAssignableFrom(clazz) || clazz.isInterface() || clazz.isArray() || ClassUtils.isPrimitiveOrWrapper(clazz) || clazz == String.class || clazz == Date.class || clazz == Object.class);
}

 

 

Published at DZone with permission of Bozhidar Bozhanov, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)