Ce contenu n'est pas disponible dans la langue sélectionnée.
12.2. Using the Infinispan CDI Module
- To configure and inject Infinispan caches into CDI Beans and Java EE components.
- To configure cache managers.
- To control storage and retrieval using CDI annotations.
12.2.1. Configure and Inject Infinispan Caches Copier lienLien copié sur presse-papiers!
12.2.1.1. Inject an Infinispan Cache Copier lienLien copié sur presse-papiers!
public class MyCDIBean {
@Inject
Cache<String, String> cache;
}
12.2.1.2. Inject a Remote Infinispan Cache Copier lienLien copié sur presse-papiers!
public class MyCDIBean {
@Inject
RemoteCache<String, String> remoteCache;
}
12.2.1.3. Set the Injection's Target Cache Copier lienLien copié sur presse-papiers!
- Create a qualifier annotation.
- Add a producer class.
- Inject the desired class.
12.2.1.3.1. Create a Qualifier Annotation Copier lienLien copié sur presse-papiers!
Example 12.1. Custom Cache Qualifier
@javax.inject.Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SmallCache {}
@SmallCache qualifier to specify how to create specific caches.
12.2.1.3.2. Add a Producer Class Copier lienLien copié sur presse-papiers!
@SmallCache qualifier (created in the previous step) specifies a way to create a cache:
Example 12.2. Using the @SmallCache Qualifier
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.cdi.ConfigureCache;
import javax.enterprise.inject.Proces;
public class CacheCreator {
@ConfigureCache("smallcache")
@SmallCache
@Produces
public Configuration specialCacheCfg() {
return new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(10)
.build();
}
}
@ConfigureCachespecifies the name of the cache.@SmallCacheis the cache qualifier.
12.2.1.3.3. Inject the Desired Class Copier lienLien copié sur presse-papiers!
@SmallCache qualifier and the new producer class to inject a specific cache into the CDI bean as follows:
public class MyCDIBean {
@Inject @SmallCache
Cache<String, String> mySmallCache;
}
12.2.2. Configure Cache Managers with CDI Copier lienLien copié sur presse-papiers!
12.2.2.1. Specify the Default Configuration Copier lienLien copié sur presse-papiers!
Example 12.3. Specifying the Default Configuration
public class Config {
@Produces
public Configuration defaultEmbeddedConfiguration () {
return new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(100)
.build();
}
}
Note
@Default qualifier if no other qualifiers are provided.
@Produces annotation is placed in a method that returns a Configuration instance, the method is invoked when a Configuration object is required.
12.2.2.2. Override the Creation of the Embedded Cache Manager Copier lienLien copié sur presse-papiers!
After a producer method is annotated, this method will be called when creating an EmbeddedCacheManager, as follows:
Example 12.4. Create a Non Clustered Cache
public class Config {
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultEmbeddedCacheManager() {
Configuration cfg = new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(150)
.build();
return new DefaultCacheManager(cfg);
}
}
@ApplicationScoped annotation specifies that the method is only called once.
The following configuration can be used to create an EmbeddedCacheManager that can create clustered caches.
Example 12.5. Create Clustered Caches
public class Config {
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultClusteredCacheManager() {
GlobalConfiguration g = new GlobalConfigurationBuilder()
.clusteredDefault()
.transport()
.clusterName("InfinispanCluster")
.build();
Configuration cfg = new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(150)
.build();
return new DefaultCacheManager(g, cfg);
}
}
The method annotated with @Produces in the non clustered method generates Configuration objects. The methods in the clustered cache example annonated with @Produces generate EmbeddedCacheManager objects.
EmbeddedCacheManager and injects it into the code at runtime.
Example 12.6. Generate an EmbeddedCacheManager
...
@Inject
EmbeddedCacheManager cacheManager;
...
12.2.2.3. Configure a Remote Cache Manager Copier lienLien copié sur presse-papiers!
RemoteCacheManager is configured in a manner similar to EmbeddedCacheManagers, as follows:
Example 12.7. Configuring the Remote Cache Manager
public class Config {
@Produces
@ApplicationScoped
public RemoteCacheManager defaultRemoteCacheManager() {
Configuration conf = new ConfigurationBuilder().addServer().host(ADDRESS).port(PORT).build();
return new RemoteCacheManager(conf);
}
}}
12.2.2.4. Configure Multiple Cache Managers with a Single Class Copier lienLien copié sur presse-papiers!
Example 12.8. Configure Multiple Cache Managers
public class Config {
@Produces
@ApplicationScoped
public org.infinispan.manager.EmbeddedCacheManager
defaultEmbeddedCacheManager() {
Configuration cfg = new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(150)
.build();
return new DefaultCacheManager(cfg);
}
@Produces
@ApplicationScoped
@DefaultClustered
public org.infinispan.manager.EmbeddedCacheManager
defaultClusteredCacheManager() {
GlobalConfiguration g = new GlobalConfigurationBuilder()
.clusteredDefault()
.transport()
.clusterName("InfinispanCluster")
.build();
Configuration cfg = new ConfigurationBuilder()
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(150)
.build();
return new DefaultCacheManager(g, cfg);
}
@Produces
@ApplicationScoped
@DefaultRemote
public RemoteCacheManager
defaultRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.Configuration conf = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder().addServer().host(ADDRESS).port(PORT).build();
return new RemoteCacheManager(conf);
}
@Produces
@ApplicationScoped
@RemoteCacheInDifferentDataCentre
public RemoteCacheManager newRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.Configuration confid = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder().addServer().host(ADDRESS_FAR_AWAY).port(PORT).build();
return new RemoteCacheManager(confid);
}
}
12.2.3. Storage and Retrieval Using CDI Annotations Copier lienLien copié sur presse-papiers!
12.2.3.1. Configure Cache Annotations Copier lienLien copié sur presse-papiers!
javax.cache package.
12.2.3.2. Enable Cache Annotations Copier lienLien copié sur presse-papiers!
beans.xml file. Adding the following code adds interceptors such as the CacheResultInterceptor, CachePutInterceptor, CacheRemoveEntryInterceptor and the CacheRemoveAllInterceptor:
Example 12.9. Adding Interceptors
<beans xmlns="http://java.sun.som/xml/ns/javaee"
xmlns:xsi="http://www/w3/org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd" >
<interceptors>
<class>
org.infinispan.cdi.interceptor.CacheResultInterceptor
</class>
<class>
org.infinispan.cdi.interceptor.CachePutInterceptor
</class>
<class>
org.infinispan.cdi.interceptor.CacheRemoveEntryInterceptor
</class>
<class>
org.infinispan.cdi.interceptor.CacheRemoveAllInterceptor
</class>
</interceptors>
</beans>
Note
beans.xml file for Red Hat JBoss Data Grid to use javax.cache annotations.
12.2.3.3. Caching the Result of a Method Invocation Copier lienLien copié sur presse-papiers!
public String toCelsiusFormatted(float fahrenheit) {
return
NumberFormat.getInstance()
.format((fahrenheit * 5 / 9) - 32)
+ " degrees Celsius";
}
toCelsiusFormatted method again and stores the result in the cache.
float f = getTemperatureInFahrenheit();
Cache<Float, String>
fahrenheitToCelsiusCache = getCache();
String celsius =
fahrenheitToCelsiusCache = get(f);
if (celsius == null) {
celsius = toCelsiusFormatted(f);
fahrenheitToCelsiusCache.put(f, celsius);
}
@CacheResult annotation instead, as follows:
@javax.cache.interceptor.CacheResult
public String toCelsiusFormatted(float fahrenheit) {
return NumberFormat.getInstance()
.format((fahrenheit * 5 / 9) - 32)
+ " degrees Celsius";
}
toCelsiusFormatted() method call.
Note
12.2.3.3.1. Specify the Cache Used Copier lienLien copié sur presse-papiers!
cacheName) to the @CacheResult annotation to specify the cache to check for results of the method call:
@CacheResult(cacheName = "mySpecialCache")
public String doSomething(String parameter) {
<!-- Additional configuration information here -->
}
12.2.3.3.2. Cache Keys for Cached Results Copier lienLien copié sur presse-papiers!
@CacheResult annotation creates a key for the results fetched from a cache. The key consists of a combination of all parameters in the relevant method.
@CacheKey annotation as follows:
Example 12.10. Create a Custom Key
@CacheResult
public String doSomething
(@CacheKey String p1,
@CacheKey String p2,
String dontCare) {
<!-- Additional configuration information here -->
}
p1 and p2 are used to create the cache key. The value of dontCare is not used when determining the cache key.
12.2.3.3.3. Generate a Custom Key Copier lienLien copié sur presse-papiers!
import javax.cache.annotation.CacheKey;
import javax.cache.annotation.CacheKeyGenerator;
import javax.cache.annotation.CacheKeyInvocationContext;
import java.lang.annotation.Annotation;
public class MyCacheKeyGenerator implements CacheKeyGenerator {
@Override
public CacheKey generateCacheKey(CacheKeyInvocationContext<? extends Annotation> ctx) {
return new MyCacheKey(
ctx.getAllParameters()[0].getValue()
);
}
}
cacheKeyGenerator to the @CacheResult annotation as follows:
@CacheResult(cacheKeyGenerator = MyCacheKeyGenerator.class)
public void doSomething(String p1, String p2) {
<!-- Additional configuration information here -->
}
p1 contains the custom key.
12.2.4. Cache Operations Copier lienLien copié sur presse-papiers!
12.2.4.1. Update a Cache Entry Copier lienLien copié sur presse-papiers!
@CachePut annotation is invoked, a parameter (normally passed to the method annotated with @CacheValue) is stored in the cache.
Example 12.11. Sample @CachePut Annotated Method
import javax.cache.annotation.CachePut
@CachePut (cacheName = "personCache")
public void updatePerson
(@CacheKey long personId,
@CacheValue Person newPerson) {
<!-- Additional configuration information here -->
}
cacheName and cacheKeyGenerator in the @CachePut method. Additionally, some parameters in the invoked method may be annotated with @CacheKey to control key generation.
12.2.4.2. Remove an Entry from the Cache Copier lienLien copié sur presse-papiers!
@CacheRemoveEntry annotated method that is used to remove an entry from the cache:
Example 12.12. Removing an Entry from the Cache
import javax.cache.annotation.CacheRemoveEntry
@CacheRemoveEntry (cacheName = "cacheOfPeople")
public void changePersonName
(@CacheKey long personId,
string newName {
<!-- Additional configuration information here -->
}
cacheName and cacheKeyGenerator attributes.
12.2.4.3. Clear the Cache Copier lienLien copié sur presse-papiers!
@CacheRemoveAll method to clear all entries from the cache.
Example 12.13. Clear All Entries from the Cache with @CacheRemoveAll
import javax.cache.annotation.CacheResult
@CacheRemoveAll (cacheName = "statisticsCache")
public void resetStatistics() {
<!-- Additional configuration information here -->
}
cacheName attribute.