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

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

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • A Practical Guide to Creating a Spring Modulith Project
  • Providing Enum Consistency Between Application and Data
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Trending

  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Measuring the Impact of AI on Software Engineering Productivity
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Agentic AI for Automated Application Security and Vulnerability Management
  1. DZone
  2. Coding
  3. Frameworks
  4. Caching With Spring Boot and Hazelcast

Caching With Spring Boot and Hazelcast

In this article, I’ll explain step-by-step how to enable Hazelcast as a cache manager for your Spring Boot application.

By 
Rafał Leszko user avatar
Rafał Leszko
·
Jul. 27, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
18.1K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Boot is very well integrated with Hazelcast. It’s enough to provide Hazelcast configuration on the classpath and it will be automatically used. In this blog post, I’ll explain step-by-step how to enable Hazelcast as a cache manager for your Spring Boot application.

Source code from this blog is posted on the Hazelcast guide repository on Github.

Spring Boot Application

To use caching in your Spring Boot application, you need to:

  • Add org.springframework.boot:spring-boot-starter-cache dependency
  • Add @EnableCaching annotation to your main class
  • Add @Cacheable("books") annotation to every method you want to cache

For more explanation on the Spring Boot cache topic, please check the official Caching Data with Spring guide.

In our case, let’s have a simple web service with two classes defined as follows.

Java
 




x
12


 
1
// BookController.java
2
@RestController
3
@RequestMapping("/books")
4
public class BookController {
5
    @Autowired
6
    private BookService bookService;
7

          
8
    @GetMapping("/{isbn}")
9
    public String getBookNameByIsbn(@PathVariable("isbn") String isbn) {
10
        return bookService.getBookNameByIsbn(isbn);
11
    }
12
}


Java
 




xxxxxxxxxx
1
18


 
1
// BookService.java
2
@Service
3
public class BookService {
4
    @Cacheable("books")
5
    public String getBookNameByIsbn(String isbn) {
6
        return findBookInSlowSource(isbn);
7
    }
8

          
9
    private String findBookInSlowSource(String isbn) {
10
        // some long processing
11
        try {
12
            Thread.sleep(3000);
13
        } catch (InterruptedException e) {
14
            e.printStackTrace();
15
        }
16
        return "Sample Book Name";
17
    }
18
}



If we started the application, then every call to the endpoint /books/<isbn> would go to the method findBookNameByIsbn() which in turn would first check the cache. Only if it does not find value in the cache, the method findBookInSlowSource() would be executed.

Using Hazelcast as Cache Manager

We want to use Hazelcast as the cache manager. The good news is that all you have to do it to add Hazelcast to your classpath.

XML
 




xxxxxxxxxx
1


 
1
<!-- pom.xml -->
2
<dependency>
3
    <groupId>com.hazelcast</groupId>
4
    <artifactId>hazelcast-all</artifactId>
5
    <version>4.0.2</version>
6
</dependency>



Then, you need to add Hazelcast configuration in one of the following manners:

  • Add hazelcast.yaml configuration OR
  • Add hazelcast.xml configuration OR
  • Define @Bean with Hazelcast configuration in the source code

Let’s use the first option and add the following file into src/main/resources.

YAML
 




xxxxxxxxxx
1


 
1
# hazelcast.yaml
2
hazelcast:
3
  network:
4
    join:
5
      multicast:
6
        enabled: true



No more configuration needed, Hazelcast is already used as the cache manager in your project!

Starting the Application

To start the application, run the following command.

mvn spring-boot:run

You should see in the logs that embedded Hazelcast has started.

Members {size:1, ver:1} [ 

Member [172.30.63.9]:5701 - 75cd0b19-ee36-4e0a-9d9c-38c49f67f842 this ]

Testing the Application

You can test the application by executing the following command.

curl locahost:8080/books/123

Sample Book Name

The first time you execute this command it should take some time to get the response. However, when you try it again, it’s instant. That means that the cache is used.

curl locahost:8080/books/123

Sample Book Name

What’s More?

Spring Boot is really well integrated with Hazelcast and vice-versa. If you want to use Hazelcast in the client-server topology, then it’s enough if you create hazelcast-client.yaml file instead of hazelcast.yaml on your classpath. And that’s it! You configured Hazelcast client.

To read more check out the official documentation Spring Boot: Hazelcast.

Spring Framework Spring Boot Hazelcast Cache (computing) application

Published at DZone with permission of Rafał Leszko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • A Practical Guide to Creating a Spring Modulith Project
  • Providing Enum Consistency Between Application and Data
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

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!