Redis

Installing Redis using Docker

docker pull redis
docker run -p 6379:6379 -d --name redis-cache redis

Note : use the following command if you need to save configuration files in host server not in container:
docker run -p 6379:6379 -d --name redis-cache -v /Users/mac/configs :/usr/redis_config redis redis-server /usr/local/etc/redis/redis.conf

Access redis-cli

docker exec -it redis-cache /bin/bash
redis-cli

Some usefull redis-cli commands

redis-cli info stats : show information about redis
redis-cli info memory: show information about memory
redis-cli ping : check resdis service
redis-cli flushall : clear all cached data

Applying Redis in Micro-service

  • Add Spring Data Redis as a dependency in your project
  • Add the following properties in application.properties
    spring.cache.type=redis
    spring.cache.type=none : if you do not have redis in local env.
    spring.redis.host=localhost
    spring.redis.port=6379
  • Add @EnableCaching into your Application class
  • Apply cashing Annotations for service layer as in below service class sample
        @Override
	@Cacheable(value = "allUsersCache")
	public List<User> findAll() {
		log.info("UserService :: findAll");
		return repository.findAll();
	}

	
	@Override
	@Cacheable(value = "allUsersCache", key = "'wtihParam_'.concat(#param)")
	public List<User> findAllWithParam(String param) {
		log.info("UserService :: findAll");
		return repository.findAll();
	}
	
	@Override
	@Cacheable(value = "userCache", key="#userId")
	public User findOne(int userId) {
		log.info("UserService :: findOne");
		return repository.getOne(userId);
	}
	
	@Override
	@Caching(put= { @CachePut(value= "userCache", key= "#user.id") },
	        evict= { @CacheEvict(value= "allUsersCache", allEntries= true) })
	public User save(User user) {
		log.info("UserService :: save");
		User createdUser = repository.saveAndFlush(user);
		sender.send(USER_CREATED_TOPIC, createdUser);
		return createdUser;
	}
	
	@Override
	@Caching(evict= { @CacheEvict(value= "userCache", key= "#userId"),
			   @CacheEvict(value= "allUsersCache", allEntries= true)})
	public void delete(@PathVariable int userId) {
		log.info("UserService :: delete");
		repository.deleteById(userId);
		
	}

        @Override
	@Caching(put= { @CachePut(value= "userCache", key= "#user.id") },
	         evict= { @CacheEvict(value= "allUsersCache", allEntries= true) })
	public User update(User user) {
		log.info("UserService :: update");
		User u = repository.getOne(user.getId());
		u.setName(user.getName());
		return repository.save(u);
	} 

References: