2

We have Infinispan 10.8.1 configured to work as a Hibernate second-level cache (2LC) in my Spring Boot application and it works as expected. The configuration is done in an infinispan.xml, with a transport configuration that points to a cluster.xml file that configures JGroups to setup a cluster of 4 machines using TCP.

We would like to use Infinispan in the code as well, to cache random instances that don't need to be persisted. However, we didn't find a way to reuse the same cache and cluster used by Hibernate, so the application does not end up creating a second cluster.

Pointing to the exact same configuration files used by Hibernate didn't prevent the application from creating a second cacheManager. How the existing cacheManager can be reused?

1 Answer 1

3

It is possible to dig into Hibernate (starting with an org.hibernate.SessionFactory) and extract the underlying cache manager like this:

    final SessionFactoryImpl factory = (SessionFactoryImpl)sessionFactory;
    final CacheImplementor cache = factory.getCache();
    final InfinispanRegionFactory regionFactory = (InfinispanRegionFactory)cache.getRegionFactory();
    final EmbeddedCacheManager cacheManager = regionFactory.getCacheManager();

Now you have a cacheManager you can call cacheManager.createCache to create your own cache, and then call cache.put and cache.get, etc.

This does a bit of unchecked casting and I would say it's very likely to change when you upgrade Hibernate or Ininispan in future.

An alternate way may be to extend InfinispanRegionFactory with your own version and override methods such that you can create your own caches at that point. You will need to change configuration hibernate.cache.region.factory_class to point at your class in this case.

Sign up to request clarification or add additional context in comments.

2 Comments

Although possible, I would not reuse Infinispan caches in Hibernate for other uses, since the cache is configured particularly for that use case. The cache manager could be reused within a Spring Boot relatively safely though. In WildFly multiple cache managers can be built on top of a single JGroups cluster.
I agree messing with the hibernate caches is a bad idea. It seems ok to use the same cache manager, but with caches for other application features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.