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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. Replacing a JSON Message Converter With MessagePack

Replacing a JSON Message Converter With MessagePack

Bozhidar Bozhanov user avatar by
Bozhidar Bozhanov
·
Apr. 26, 12 · Interview
Like (0)
Save
Tweet
Share
9.43K 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.

Popular on DZone

  • gRPC on the Client Side
  • Debezium vs DBConvert Streams: Which Offers Superior Performance in Data Streaming?
  • 10 Most Popular Frameworks for Building RESTful APIs
  • Apache Kafka Is NOT Real Real-Time Data Streaming!

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: