Configure JBOSS Infinispan for using hibernate level 2 caching

1.4k views Asked by At

How to configure JBOSS Infinispan for using hibernate level 2 caching. I am using Spring Boot Application and Spring Data JPA is been used which has been configured to use Hibernate. My application does not have any kind of xml file.I am new to this caching.So please provide the detail solution for this.

2

There are 2 answers

2
Elvis Rocha On

Firstly, add the dependencies to your pom.xml:

<dependency>
    <groupId>org.infinispan</groupId>
<artifactId>infinispan-spring4-embedded</artifactId>
</dependency>
<dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-jcache</artifactId>
</dependency>

Then put this file (infinispan.xml) in your resources folder:

<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns="urn:infinispan:config:7.2">
    <cache-container default-cache="default">
        <local-cache name="countries" statistics="true">
            <eviction max-entries="200"/>
            <expiration lifespan="600000"/>
        </local-cache>
    </cache-container>
</infinispan>

Add to the resources folder the file (application.properties) too:

spring.cache.infinispan.config=infinispan.xml

Then you add the cache where you want, for example:

@Component
@CacheConfig(cacheNames = "countries")
public class CountryRepository {

    @Cacheable
    public Country findByCode(String code) {
        System.out.println("---> Loading country with code '" + code + "'");
        return new Country(code);
    }

}

Don't forget to enable cache in your Main class:

@EnableCaching
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
    }
}

There's also a spring boot starter for Infinispan that you can try it if you want.

<dependencies>
    <dependency>
        <groupId>org.infinispan</groupId>
        <artifactId>inifinispan-spring-boot-starter</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>

Using the starter you need only set the Spring cache () in your applicationContext.xml. Create a bean of class SpringEmbeddedCacheManagerFactoryBean. Then you can annotate the classes you want with @Cacheable.

Examples here: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-cache

9
Radim Vansa On

1) make sure that hibernate-infinispan (with transitive dependencies) is on classpath

2) set

hibernate.cache.use_second_level_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.infinispan.InfinispanRegionFactory
hibernate.cache.default_cache_concurrency_strategy = TRANSACTIONAL
javax.persistence.sharedCache.mode = ALL

You might also need to set hibernate.transaction.jta.platform and hibernate.transaction.coordinator_class if Spring does not do that for you automatically.