Shared Hibernate 5 second-level cache with Hazelcast

Viewed 635

I'm trying to implement a shared second-level Hibernate cache using JCache and Hazelcast.

The goal is to have multiple servers joined in a Hazelcast cluster sharing the same Hibernate second-level cache, so when Hibernate on one of the servers (nodes) updates the cache, all other servers (nodes) have their second-level cache updated as well. I have managed to establish a Hazelcast cluster with two nodes, where each one "sees" the second-level cache of another.

The problem is that each of the nodes is still using its own cache so when one of them updates the cache, another continues to fetch old (unchanged) entries from its "outdated" cache. In other words - I have two second-level caches distributed between two nodes with each node using a different cache.

I'm using Hazelcast 4.2, Hibernate 5.4, Spring Boot 2.4.8

These are my spring-boot properties:

spring.jpa.properties.hibernate.generate_statistics          = true
spring.jpa.properties.hibernate.cache.use_second_level_cache = true
spring.jpa.properties.hibernate.cache.use_query_cache        = true
spring.jpa.properties.javax.persistence.sharedCache.mode     = ENABLE_SELECTIVE
spring.jpa.properties.hibernate.cache.region.factory_class   = jcache
spring.jpa.properties.hibernate.javax.cache.provider         = com.hazelcast.cache.impl.HazelcastServerCachingProvider
spring.jpa.properties.hibernate.javax.cache.uri              = classpath:hazelcast.xml

Sample cache configuration in hazelcast.xml:

<cache name="jobsCache">
    <statistics-enabled>true</statistics-enabled>
    <management-enabled>true</management-enabled>
    <eviction size="200" max-size-policy="ENTRY_COUNT" eviction-policy="LRU" />
    <expiry-policy-factory>
        <timed-expiry-policy-factory expiry-policy-type="CREATED" duration-amount="10" time-unit="MINUTES"/>
    </expiry-policy-factory>
</cache>

Am I missing some configuration or have done something wrong?

Thank you!

1 Answers

You need to consider the cache strategy CacheConcurrencyStrategy If your cache data is updated frequently, and you want it to be updated on all instances, then use CacheConcurrencyStrategy. READ_WRITE

Related