Spring Boot, JCache and Hazelcast!
Introduction
This post is about using JCache API/Hazelcast implementation in Spring Boot application.
This exercise is based on the sample from Hazelcast team available at GitHub Hazelcast Code Samples Repository.
Will use Maven as our build and dependency management tool.
Definitions
- JCache (JSR 107) is a common API for using caching in Java.
- Hazelcast is an open source In-Memory Data Grid product. It is also a full implementation of JCache(JSR 107).
- Spring Boot is an opionated version of Spring Framework which combines many other Spring projects.
Steps
1. Configure your Spring Boot project.
2. Add caching starter to your Spring Boot project:
3. Add JCache API to your classpath:
4. Add Hazelcast to the classpath:
5. Specify cache type and jcache provider in application.properties configuration file:
6. Add hazelcast.xml to the classpath and define your cache there, ex.:
7. Add @EnableCaching
annotation to your configuration class.
8. Disable auto configuration for Hazelcast in your Spring Boot application configuration class:
9. Use JCache(JSR107) annotation to annotate your cache targets, ex:
10. Enjoy caching!
Details and nuances
If you add Hazelcast to the classpath of Spring Boot project, then Spring Boot automatically configures one Hazelcast instance in its context. We don’t need this instance - we need only JCache manager and provider to be initialized following standard JCache approach. That’s why we need step #8 - other wise will endup havenig 2 Hazelcast instances in our application: