Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Replacing a JSON Message Converter With MessagePack

DZone's Guide to

Replacing a JSON Message Converter With MessagePack

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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);
}

 

 

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Published at DZone with permission of Bozhidar Bozhanov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}