Enterprise Java

Jolokia Spring Boot Integration Example

Monitoring and managing Spring Boot applications can be greatly enhanced using tools like Jolokia, which exposes JMX MBeans over HTTP. While Spring Boot offers Actuator endpoints for health checks and metrics, Jolokia provides a bridge for accessing JMX data in a more firewall-friendly, JSON-based REST API format. Let us delve into understanding Jolokia Spring Boot integration and how it can simplify the monitoring and management of your Spring Boot applications.

1. What is Jolokia?

Jolokia is an open-source JMX (Java Management Extensions)HTTP bridge that enables remote access to Java Management Extensions (JMX) MBeans via HTTP using JSON. It provides a modern and convenient alternative to traditional JSR-160 connectors, simplifying the management and monitoring of Java applications in distributed environments.

Unlike standard JMX connectors, which typically use complex protocols like RMI, Jolokia leverages HTTP/S for communication, making it much easier to use in environments with strict firewall rules or proxies.

1.1 Key features of Jolokia

  • Firewall-friendly communication: Since Jolokia uses standard HTTP and HTTPS protocols, it easily passes through firewalls and proxies without requiring special configuration.
  • Lightweight JSON payloads: Data is transmitted using JSON, which is more compact and easier to parse compared to the XML-based JMX protocol, reducing overhead and improving performance.
  • Support for bulk operations: Jolokia allows querying or invoking multiple MBeans or attributes in a single HTTP request, optimizing network usage and response time.
  • Easy integration with modern monitoring tools: Due to its RESTful API and JSON format, Jolokia integrates seamlessly with popular monitoring solutions like Prometheus, Grafana, and custom dashboards.
  • Platform and language agnostic: While designed for Java applications, any client capable of making HTTP requests and handling JSON can interact with Jolokia.
  • Secure communication: Supports HTTPS and various authentication mechanisms, enabling secure management access in production environments.

Overall, Jolokia simplifies the process of monitoring and managing Java applications, especially in cloud-native, containerized, or microservices architectures where traditional JMX access can be challenging.

2. Code Example

This section demonstrates a practical example of integrating Jolokia with a Spring Boot application. Jolokia acts as a JMX-over-HTTP bridge, enabling monitoring and managing Java applications remotely via HTTP. This is especially useful in microservices or cloud environments where direct JMX access can be challenging.

2.1 Add Dependencies (pom.xml)

To integrate Jolokia into your Spring Boot project, you must include the necessary dependencies in your pom.xml. The spring-boot-starter-actuator provides production-ready features including endpoint exposure and health checks. The jolokia-core library enables Jolokia’s JMX-HTTP bridge functionality. Adding these dependencies prepares your application to expose Jolokia endpoints.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
  <groupId>org.jolokia</groupId>
  <artifactId>jolokia-core</artifactId>
  <version>latest__jar__version</version>
</dependency>

2.2 Enable Jolokia in application.properties

Configure your Spring Boot application to expose the Jolokia endpoint by updating application.properties. Here, you specify which actuator endpoints are exposed over HTTP and explicitly enable the Jolokia endpoint. Basic authentication is configured for security to protect your management endpoints from unauthorized access. Additionally, the server port is set for convenience.

# Expose Jolokia actuator endpoint
management.endpoints.web.exposure.include=health,info,jolokia

# Enable Jolokia actuator endpoint explicitly
management.endpoint.jolokia.enabled=true

# Set basic auth user
spring.security.user.name=admin
spring.security.user.password=admin123

# Server port
server.port=8080

2.3 Creating Main Class

The main class bootstraps the Spring Boot application using the @SpringBootApplication annotation, which triggers component scanning and auto-configuration. Running this class launches the embedded server and activates all Spring components, including Jolokia support.

package com.example.jolokia;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JolokiaSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(JolokiaSpringBootApplication.class, args);
    }
}

2.4 MBean Interface

In JMX, managed resources are defined through MBeans (Managed Beans). Here, the HelloMBean interface declares two operations: sayHello() returns a greeting string, and add(int x, int y) performs a simple addition. This interface defines the contract for the MBean that will be exposed.

package com.example.jolokia.mbean;

public interface HelloMBean {
    String sayHello();
    int add(int x, int y);
}

2.5 MBean Implementation

The Hello class implements the HelloMBean interface, providing concrete behavior for the declared operations. Once registered with the MBean server, these methods will be remotely accessible via Jolokia.

package com.example.jolokia.mbean;

public class Hello implements HelloMBean {

    @Override
    public String sayHello() {
        return "Hello from Jolokia MBean!";
    }

    @Override
    public int add(int x, int y) {
        return x + y;
    }
}

2.6 MBean Registration Configuration

To make the Hello MBean available for remote management, it must be registered with the platform MBean server. This configuration class registers the MBean during Spring’s startup lifecycle using the @PostConstruct annotation. It checks if the MBean is already registered to avoid duplication.

package com.example.jolokia.config;

import com.example.jolokia.mbean.Hello;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

@Configuration
public class MBeanConfig {

    @PostConstruct
    public void registerMBean() throws Exception {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName("com.example.jolokia.mbean:type=Hello");
        Hello mbean = new Hello();

        if (!mbs.isRegistered(name)) {
            mbs.registerMBean(mbean, name);
        }
    }
}

2.7 Security Configuration

For security, this configuration enables HTTP Basic authentication specifically for the Jolokia actuator endpoints. All requests to the Jolokia endpoint require authentication, while other requests are permitted without restriction. CSRF protection is disabled here for simplicity, which is common in actuator endpoints but should be reviewed for production use.

package com.example.jolokia.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          .authorizeHttpRequests(auth -> auth
            .requestMatchers("/actuator/jolokia/**").authenticated()
            .anyRequest().permitAll()
          )
          .httpBasic()
          .and()
          .csrf().disable(); // Disable CSRF for simplicity on actuator endpoints

        return http.build();
    }
}

2.8 Run the application

After configuring and implementing the application, build it with Maven and run the resulting jar file. Once started, you can access the Jolokia endpoints over HTTP using the configured basic authentication credentials. The following examples demonstrate how to query the MBean and invoke its operations using curl.

-- Step 1
mvn clean package

-- Step 2
java -jar target/jolokia-springboot-0.0.1-SNAPSHOT.jar

2.8.1 Accessing Jolokia Endpoints with Basic Authentication

Once the Spring Boot application is running and Jolokia is properly configured and secured, you can interact with the exposed MBeans remotely using HTTP requests. Jolokia provides a RESTful API to perform JMX operations over HTTP. Since we enabled basic authentication in the security configuration, you need to provide valid credentials to access these endpoints.

2.8.1.1 Reading MBean Attributes

The following curl command performs an HTTP GET request to read the available operations and attributes exposed by the Hello MBean. Notice the use of -u admin:admin123 which supplies the basic authentication username and password.

-- Request
curl -u admin:admin123 http://localhost:8080/actuator/jolokia/read/com.example.jolokia.mbean:type=Hello

-- Response
{
  "request": {
    "mbean": "com.example.jolokia.mbean:type=Hello",
    "type": "read"
  },
  "value": {
    "SayHello": "operation",
    "Add": "operation"
  },
  "status": 200,
  "timestamp": 1715768294000
}
2.8.1.2 Invoking an MBean Operation

To invoke an operation exposed by the MBean, you send a POST request with a JSON payload describing the action. Here, we invoke the sayHello method remotely. The Content-Type header is set to application/json, and the body specifies the type of operation (exec for execute), the MBean object name, and the operation name.

-- Request
curl -u admin:admin123 -H "Content-Type: application/json" -X POST \
  -d '{"type":"exec","mbean":"com.example.jolokia.mbean:type=Hello","operation":"sayHello"}' \
  http://localhost:8080/actuator/jolokia

-- Response
{
  "request": {
    "type": "exec",
    "mbean": "com.example.jolokia.mbean:type=Hello",
    "operation": "sayHello"
  },
  "value": "Hello from Jolokia MBean!",
  "status": 200,
  "timestamp": 1715768294000
}

This example demonstrates how Jolokia makes it straightforward to remotely read and invoke JMX MBeans via simple HTTP calls secured with basic authentication.

3. Conclusion

Integrating Jolokia with Spring Boot offers a powerful and flexible way to monitor and manage your Java application. Exposing MBeans via HTTP in a JSON format, it makes JMX data more accessible for web-based monitoring systems. Combined with Spring Security, you can safely expose only the management endpoints you need. Jolokia is especially useful in environments where traditional JMX access (RMI) is impractical, such as containerized or cloud-native deployments.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button