4.2. Converting data on demand with embedded caches
Embedded caches have a default request encoding of application/x-java-object and a storage encoding that corresponds to the media type that you configure for the cache. This means that Data Grid marshalls POJOs from the application to the storage encoding for the cache and then returns POJOs back to the application. In some complex scenarios you can use the AdvancedCache API to change the default conversion to and from POJOs to other encodings.
The following example uses the withMediaType() method to return values as application/json on demand.
Advanced cache with MediaType
DefaultCacheManager cacheManager = new DefaultCacheManager();
// Encode keys and values as Protobuf
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.encoding().key().mediaType("application/x-protostream");
cfg.encoding().value().mediaType("application/x-protostream");
cacheManager.defineConfiguration("mycache", cfg.build());
Cache<Integer, Person> cache = cacheManager.getCache("mycache");
cache.put(1, new Person("John","Doe"));
// Use Protobuf for keys and JSON for values
Cache<Integer, byte[]> jsonValuesCache = (Cache<Integer, byte[]>) cache.getAdvancedCache().withMediaType("application/x-protostream", "application/json");
byte[] json = jsonValuesCache.get(1);
Value returned in JSON format
{
"_type":"org.infinispan.sample.Person",
"name":"John",
"surname":"Doe"
}