Redis + Pool de conexão + Spring

This post show how to create a Redis connection pool using Spring Framework.

Maven dependency

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.7.0</version>
</dependency>

Spring Configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/task/spring-context-3.0.xsd
               http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">						

  <bean id="poolRedisConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">

<property name="maxTotal" value="128"/>
  </bean>

  <bean id="poolRedis" class="redis.clients.jedis.JedisPool">
    <constructor-arg ref="poolRedisConfig" index="0" />
    <constructor-arg value="localhost" index="1" type="java.lang.String" />
    <constructor-arg value="6379" index="2" type="int" />
  </bean>

</beans>

Implementation Example

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisService {

@Autowired
@Qualifier("poolRedis")
private JedisPool jedisPool;

public List find(Long key){
Jedis jedisCliente = jedisPool.getResource();

//my Redis Operations

jedisCliente.close();
return null;
}
}