Wednesday, August 12, 2015

Using Redis cache

Installation:

Follow the instruction at: Install Redis cache in linux - DigitalOcean

Using Redis cache:

Create bean:
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${atm.cache.redis.host}"
          p:port="${atm.cache.redis.port}"
          p:poolConfig-ref="jedisPoolConfig"
          p:usePool="true"/>
 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connectionFactory-ref="jedisConnFactory" p:keySerializer-ref="stringRedisSerializer"/>

 Autowired in java implement:
@Autowired
private RedisTemplate<String, ProgramBasicInfo> programRedisTemplate;

Delete all cache: (in this case, it get connection and then flush all data)
programRedisTemplate.getConnectionFactory().getConnection().flushAll();

Delete cache:
programRedisTemplate.opsForHash().getOperations()
                                    .delete(Constants.CACHE_PROGRAM_GUIDE_KEY);

Put data to cache:
programRedisTemplate.opsForHash().put(Constants.CACHE_PROGRAM_GUIDE_KEY, program.getProgramId(),       programBasicInfo);

Get data from cache:
(ProgramBasicInfo) programRedisTemplate.opsForHash().get(Constants.CACHE_PROGRAM_GUIDE_KEY, programId);

References:

http://blog.joshuawhite.com/java/caching-with-spring-data-redis/
http://caseyscarborough.com/blog/2014/12/18/caching-data-in-spring-using-redis/


No comments:

Post a Comment