Spring and Hessian for Fast, Easy Java Remoting

Spring and Hessian for Fast, Easy Java Remoting

he world of enterprise Java has an overwhelming array of choices for remoting: RMI, XML/SOAP, REST/JSON, etc. Each comes with its own industry-acknowledged strengths and weaknesses, such as complex setup (RMI) or performance overhead (XML/SOAP). A lesser known but very powerful and easy-to-use option is the Hessian binary web service protocol. The binary aspect of Hessian delivers excellent performance, and its native integration within Java allows you to expose remote services purely via a regular Java interface.

Hessian’s most rewarding feature, though, is the ability to pass full Java POJO object graphs from one process to another easily without the overhead of XML marshalling, an unfortunate side effect of SOAP web services. Also, Hessian is implemented in a variety of different languages, so you theoretically can execute efficient binary remoting between Java and Python or Java and C# as well.

This article walks through using the Hessian protocol as an alternative to the more widely accepted RMI, XML/SOAP, and REST/JSON approaches for remote communication. It also explains how to integrate Spring and Hessian and then create Hessian components as simple Java objects.

Basic Hessian Example

The basic Hessian setup is quite simple. You first need to externalize all the API interfaces and POJOs shared between the two endpoints into a separate JAR library, which will not contain any of the API implementation, just the interface (i.e., the contract). On the server side, Hessian provides a special HessianServlet, which you can extend to provide and expose the interface implementation. On the client side, you can use a HessianProxyFactory object to generate a local proxy of the interface from a mere URL.

The basic example from the Hessian web site illustrates this setup as follows:

Interface (shared across client and server):
public interface BasicAPI {     public String hello();}
Server implementation:
public class BasicService extends HessianServlet implements BasicAPI {  private String _greeting = "Hello, world";  public void setGreeting(String greeting)  {    _greeting = greeting;  }  public String hello()  {    return _greeting;  }}
Client:
String url = "http://hessian.caucho.com/test/test";HessianProxyFactory factory = new HessianProxyFactory();BasicAPI basic = (BasicAPI) factory.create(BasicAPI.class, url);System.out.println("hello(): " + basic.hello());

If you have done the wsdl2java and java2wsdl Ant dance when exposing services via XML/SOAP, you surely will appreciate this straightforward path to implementing a Hessian-based web service. It’s just 100% pure Java with some magic behind the scenes to tie it all together.

Spring Hessian Integration

When implementing Hessian in a Spring application, the original Hessian API does not apply. Luckily, the Spring team realized the value of Hessian a long time ago and provided solid integration for creating Hessian components as simple Java objects?without the need to extend specialized servlets.

To demonstrate Spring’s Hessian integration, this section walks you through setting up some common interfaces. First, use the following two classes to create a service that will allow saving/updating/deleting a simple Person POJO:

public class Person implements Serializable {      private Integer id;   private String firstName;   private String lastName;   private Calendar birthDate;   public Person() {      super();   }   public Person(String firstName, String lastName, Calendar birthDate) {      super();      this.firstName = firstName;      this.lastName = lastName;      this.birthDate = birthDate;     ...getters and setters...   }}
Person DAO service:
public interface IPersonService {   Person get(Integer id);   Person add(Person person);   void delete(Integer personId);   void update(Person person);}

Both these classes are part of a common library shared on both endpoints.

Setting Up the Server Endpoint

In the Spring server-side application, create a regular Java component that implements your service interface. Here’s an example of how to do that:

@Service("personService")public class PersonService implements IPersonService {   //map used for simulating data storage     private static Map people = new ConcurrentHashMap();   private static AtomicInteger keyGenerator = new AtomicInteger(0);      @Override   public Person add(Person person) {      if (person.getId() == null) {         Integer id = keyGenerator.addAndGet(1);         person.setId(id);         people.put(id,person);         return person;      } else {         throw new RuntimeException("Person already exists!");      }         }   @Override   public void update(Person person) {      if (person.getId() != null) {         people.put(person.getId(), person);      } else {         throw new RuntimeException("Person must be saved first!");      }   }      @Override   public void delete(Integer personId) {      people.remove(personId);   }   @Override   public Person get(Integer id) {      return people.get(id);   }}

As you can see, this component does not need to extend the previously mentioned Hessian servlet. Also, the @Service Spring stereotype annotation eliminates the need to explicitly define the bean in an XML configuration. However, exposing the component via Spring does involve a series of steps.

First, in web.xml, add the Spring remoting servlet and map it to a URI:

      remoting      org.springframework.web.servlet.DispatcherServlet      1            remoting      /remoting/*   

The Spring remoting servlet will expect a new Spring application context file, which is usually called remoting-servlet.xml (separate from the usual beans.xml used by the rest of the application). In the context file, you have to expose your service via a HessianServiceExporter class:

"http://www.springframework.org/schema/beans"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
> "com.devx.hessian.server"/> "/PersonService" class="org.springframework.remoting.caucho.HessianServiceExporter"> "service" ref="personService" /> "serviceInterface" value="com.dexv.hessian.IPersonService"/>

The context elements activate Spring’s new annotation-based context support (to avoid unnecessary XML configuration) and tell it which package to use as the base for searching for components. The PersonService implementation is then injected into the HessianServiceExporter class instance.

If you run the server app (from the code sample attached to this article) and access the /remoting/PersonService URI via a regular browser, you will get a notice that Hessian is listening, although unable to process a typical browser request:

HTTP ERROR: 405HessianServiceExporter only supports POST requestsRequestURI=/remoting/PersonService

Setting Up the Client

On the client side, you need to create an instance of a HessianProxyFactoryBean that points to your service URL:

"http://www.springframework.org/schema/beans"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
> "com.devx.hessian.client" /> "personService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean"> "serviceUrl" value="http://0.0.0.0:8080/remoting/PersonService" /> "serviceInterface" value="com.dexv.hessian.IPersonService" />

When your service URL is defined, you can just inject the HessianProxyFactoryBean instance into your client application using regular dependency injection:

@Component("mainClient")public class MainClient {   private IPersonService service = null;      @Autowired   public void setPersonService(@Qualifier("personService") IPersonService service) {      this.service = service;   }}

Spring 2.5 and Hessian 2 Incompatibility Alert

As of version 3.2.0, the Hessian library started using a new version of the protocol called simply Hessian 2. Unfortunately, the current production version of Spring (namely 2.5.6.SEC01) has support for the original Hessian protocol only. Therefore, if you are on Spring 2.5, the version of Hessian that you should download is 3.1.6.

Fortunately, this has been corrected in the latest milestone builds of Spring 3.0. The code samples attached to this article use the latest Hessian 4.0.1 and Spring 3.0 M4 builds.

devx-admin

devx-admin

Share the Post:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining