DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Coding
  3. Languages
  4. Replacing a JSON Message Converter With MessagePack

Replacing a JSON Message Converter With MessagePack

By 
Bozhidar Bozhanov user avatar
Bozhidar Bozhanov
·
Apr. 26, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
10.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

 

 

JSON

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

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: