星期四, 三月 05, 2015

Spring JCache support


Spring JCache support

Spring 4 provides seamless JCache integration.

Enable Caching

In this example, use EhCache as JCache specification provider.
Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration.
@Override
@Bean
public CacheManager cacheManager() {
 JCacheCacheManager cacheManager = new JCacheCacheManager();
 cacheManager.setCacheManager(new JCacheManager(
   new JCacheCachingProvider(), ehcache(), null, null));
 return cacheManager;
}

private net.sf.ehcache.CacheManager ehcache() {
 return new net.sf.ehcache.CacheManager();
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the ehcache-core, jcache, cache-api dependencies in your Maven pom.xml file.
<dependency>
 <groupId>net.sf.ehcache</groupId>
 <artifactId>ehcache-core</artifactId>
</dependency>

<dependency>
 <groupId>org.ehcache</groupId>
 <artifactId>jcache</artifactId>

</dependency>
<dependency>
 <groupId>javax.cache</groupId>
 <artifactId>cache-api</artifactId>
</dependency>

Use JCache API

Like Spring core, JCache APIs provides a series of annotations for cache operations.
@Repository
public class JpaConferenceRepositoryImpl implements ConferenceRepository {
 private static final Logger log = LoggerFactory
   .getLogger(JpaConferenceRepositoryImpl.class);

 @PersistenceContext
 private EntityManager entityManager;

 @Override
 @CacheResult(cacheName = "conference")
 public Conference findById(Long id) {
  return (Conference) entityManager.find(Conference.class, id);

 }

 @Override
 @CachePut(cacheName = "conference" )
 public Conference save(final Conference conference) {
  if (conference.isNew()) {
   entityManager.persist(conference);
   entityManager.flush();
   return conference;
  } else {
   Conference conf = entityManager.merge(conference);
   entityManager.flush();
   return conf;
  }
 }

 
 @Override
 @CacheRemove(cacheName = "conference" )
 public void delete(final Long id) {
  entityManager.remove(entityManager.find(Conference.class, id));
  entityManager.flush();
 }
 
 @Override
 @CacheRemove(cacheName = "conference" )
 public void delete(final Conference conf) {
  entityManager.remove(entityManager.merge(conf));
  entityManager.flush();
 }

 @Override
 @CacheRemoveAll(cacheName = "conference")
 public void deleteAll() {
  List<Conference> all = entityManager.createQuery("from Conference",
    Conference.class).getResultList();
  for (Conference c : all) {
   delete(c);
  }
  entityManager.flush();
 }

 @Override
 @CacheResult(cacheName = "conference")
 public Conference findBySlug(String slug) {
  List<Conference> all = entityManager
    .createQuery("from Conference where slug=:slug",
      Conference.class).setParameter("slug", slug)
    .getResultList();
  if (!all.isEmpty()) {
   return all.get(0); 
  }

  return null;
 }
}
Spring JCache support can reuse the Spring Caching configuration, but use JCache APIs in codes..

Code sample

Check out the sample codes.
And explore the spring-jcache folder.

星期三, 三月 04, 2015

Caching with Infinispan(Remote standalone server)


Spring Caching with Infinispan(Remote standalone server)

Infinispan Spring Integration provides SpringRemoteCacheManager to connect remote infinispan server.

Get JBoss Infinispan

Download a copy of JBoss Infinispan.
Install it into your local system, and make sure it is running.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration. There is a SpringRemoteCacheManager provided by Infinispan Spring integration.
@Override
@Bean
public CacheManager cacheManager() {

 return new SpringRemoteCacheManager(
   new RemoteCacheManager(   
    new ConfigurationBuilder()
     .addServer()
     .host("localhost")
     .build()
    )
   );
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the infinispan-spring dependency in your Maven pom.xml file.
<dependency>
 <groupId>org.infinispan</groupId>
 <artifactId>infinispan-spring</artifactId>
</dependency>
<dependency>
 <groupId>org.infinispan</groupId>
 <artifactId>infinispan-client-hotrod</artifactId>
</dependency>

Code sample

Check out the sample codes.
And explore the spring-cache-infinispan-remote folder.

Caching with Infinispan


Spring Caching with Infinispan

JBoss Infinispan is popular distributed caching solution, it is the base of RedHad Data Grid product.
In the real world projects, Infinispan can work in several ways.
  • Run as a standalone server.
  • Run as JBoss service.
  • Embedded.
Infinispan also provides Spring integration, and provides two different CacheManager implementations for embedded way and standalone servers.
This post focus on the embedded way, the next post will contain the standalone environment configuration.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration. There is a SpringEmbeddedCacheManager provided by Infinispan Spring integration.
@Override
@Bean
public CacheManager cacheManager() {

 return new SpringEmbeddedCacheManager(
   new DefaultCacheManager(
    new ConfigurationBuilder()
     .eviction()
      .maxEntries(20000)
      .strategy(EvictionStrategy.LIRS)
     .expiration()
      .wakeUpInterval(5000L)
      .maxIdle(120000L)
       .build()
    )
   );
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the infinispan-spring dependency in your Maven pom.xml file.
<dependency>
 <groupId>org.infinispan</groupId>
 <artifactId>infinispan-spring</artifactId>
</dependency>

Code sample

Check out the sample codes.
And explore the spring-cache-infinispan-embedded folder.

Caching with HazelCast


Spring Caching with HazelCast

HazelCast is a popular distributed caching solution, it provides Spring integration and also provides a CacheManager implementation.

Get HazelCast

HazelCast provides commercial and open source version, download an open source copy from the community HazelCast website.
Unzip it into your local system. And run it.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration.
@Override
@Bean
public CacheManager cacheManager() {
 return new HazelcastCacheManager(hazelcastInstance());
}

@Bean
public HazelcastInstance hazelcastInstance() {
 ClientNetworkConfig networkConfig = new ClientNetworkConfig()
   .addAddress("localhost");
 ClientConfig clientConfig = new ClientConfig();
 clientConfig.setNetworkConfig(networkConfig);
 return HazelcastClient.newHazelcastClient(clientConfig);
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the hazelcast dependency in your Maven pom.xml file.
<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast</artifactId>
</dependency>

Code sample

Check out the sample codes.
And explore the spring-cache-hazelcast folder.

Caching with JCache

Spring Caching with JCache

JCache is a Java EE specification which missed the Java EE 7 train, but it is ready for Java EE 8 now.
EhCache, Infinispan etc provide implementations of JCache 1.0 specification.
Spring core provides a bridge between JCache and Spring Caching abstraction.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration. There is a JCacheCacheManager provided by Spring.
But also specify JCache will use EhCache as backend implementation.
@Override
@Bean
public CacheManager cacheManager() {
 JCacheCacheManager cacheManager = new JCacheCacheManager();
 cacheManager.setCacheManager(new JCacheManager(
   new JCacheCachingProvider(), ehcache(), null, null));
 return cacheManager;
}

private net.sf.ehcache.CacheManager ehcache() {
 return new net.sf.ehcache.CacheManager();
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the ehcache dependency in your Maven pom.xml file.
<dependency>
 <groupId>net.sf.ehcache</groupId>
 <artifactId>ehcache-core</artifactId>
</dependency>
<dependency>
 <groupId>net.sf.ehcache</groupId>
 <artifactId>jcache</artifactId>
</dependency>
Note, aslo added a Ehcache Jcache dependency.

Code sample

Check out the sample codes.
And explore the spring-cache-jcache folder.

Caching with Redis


Spring Caching with Redis

Spring Data Redis project provide an CacheManager implementation for Redis.

Get Redis

Get a copy of Redis from official Redis website.
In most of linux distribution, you can install it from distribution repository directly.
Before you run you codes, make sure it is running.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, configure a Redis specific CacheManager.
@Override
@Bean
public CacheManager cacheManager() {
 RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
 return cacheManager;
}

@Bean
public RedisTemplate redisTemplate() {
 RedisTemplate redisTemplate = new RedisTemplate();
 redisTemplate.setConnectionFactory(jedisConnectionFactory());

 return redisTemplate;
}

@Bean
public JedisConnectionFactory jedisConnectionFactory() {
 // JedisPoolConfig poolConfig=new JedisPoolConfig();
 // poolConfig.set

 JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
 connectionFactory.setHostName("192.168.1.103");
 connectionFactory.setUsePool(true);
 return connectionFactory;
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the spring-data-redis dependency in your Maven pom.xml file.
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-redis</artifactId>
</dependency>

Code sample

Check out the sample codes.
And explore the spring-cache-redis folder.

Caching with GemFire


Spring Caching with Pivotal GemFire

Spring Data Gemfire project provides a CacheManager implementation for Pivotal Gemfire.

Get Gemfire

First you have to get a trial copy from Pivotal Gemfire.
Install it into your system, and make sure it runing.

Enable Caching

Add @EnableCaching(mode=AdviceMode.ASPECTJ) annotation on the configuration class if you are using Java based configuration.
@Configuration
...
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class JpaConfig {...}
Then, specify a CacheManager provider in your configuration. There is a GuavaCacheManager provided by Spring.
@Bean
CacheFactoryBean cacheFactoryBean() {
 return new CacheFactoryBean();
}

@Bean
LocalRegionFactoryBean<String, Conference> localRegionFactory(final GemFireCache cache) {
 return new LocalRegionFactoryBean<String, Conference>() {{
  setCache(cache);
  setName("conference");
 }};
}

@Override
@Bean
public CacheManager cacheManager() {
 GemfireCacheManager _cacheManager= new GemfireCacheManager();
 try {
  _cacheManager.setCache(cacheFactoryBean().getObject());
  Set<Region<?,?>> regions=new HashSet<>();
  regions.add(localRegionFactory(cacheFactoryBean().getObject()).getObject());
  _cacheManager.setRegions(regions);
 } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 
 return _cacheManager;
}

@Override
@Bean
public KeyGenerator keyGenerator() {
 return new SimpleKeyGenerator();
}
Do not forget to add the spring-data-gemfire dependency in your Maven pom.xml file.
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-gemfire</artifactId>
</dependency>

Code sample

Check out the sample codes.
And explore the spring-cache-gemfire folder.