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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • The Future of Java and AI: Coding in 2025
  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  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.5K 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
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!