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?
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.