WoooHaaaa
WoooHaaaa

Reputation: 20450

Redis : Can I init jedis instance as a static final field?

I need to use Redis as data source in Java, so I decide to use the code:

public class RedisService {
    private static final Jedis jedis = new Jedis("host",6400);;

    public static Device getDevice(String key) {
        // Do something use redis.
        return null;
    }

}

I thought the server will automatically init Jedis(Redis API for Java), it this a good way to use Jedis ?

Upvotes: 2

Views: 2905

Answers (2)

zenbeni
zenbeni

Reputation: 7193

As Santosh Joshi tried to explain: it is best to use a JedisFactory. Your Jedis which is Singleton can "die" due to network, overload etc... and you will have to restart your application to get a new connection to Redis.

To counter that, you can define a Jedis Pool and, if you don't want to use Spring (on which the solution from Santosh is based on), you can use the JedisPool class which is provided with Jedis. Then, you can define it as a singleton (as static final or via Spring for instance) and get Jedis instances from it.

As it is a pool you can get more than 1 connection to Redis at a time (you can configure that), and it supports dealing with broken connections: it creates fresh new Jedis when one is dead.

Upvotes: 2

Santosh Joshi
Santosh Joshi

Reputation: 3320

Have a look at how we are using Jedis:

  1. Create a singleton org.springframework.data.redis.connection.jedis.JedisConnectionFactory instance by passing host and port info

  2. Create singleton org.springframework.data.redis.core.RedisTemplate instance by passing the connection factory to it

  3. Use the redisTemplate created above in your service, the benefit of using Redistemplate is that you can use it perform operation across all data structures provided by redis( list, set, hashes)

Just for your reference, here's the spring code that does the same, you can use if your are using spring else you can create the same using java code

<!-- Create Factory -->
<bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
   <property name="hostName" value="localhost" />
   <property name="port" value="6370" />
   <property name="timeout" value="5000" />
</bean> 

<!-- Create Redis Template -->
<bean id="redisRemplate" class="org.springframework.data.redis.core.RedisTemplate" >
    <property name ="connectionFactory" ref="jedisFactory" />
</bean>

<!-- Your Service class -->
<bean id="serviceClass" class="RedisService" >
    <property name ="redisTemplate" ref="redisRemplate" />
</bean>

public class RedisService 
{
    private final RedisTemplate redisTemplate = /* get from  store or  inject using spring */;

    public static Device getDevice(String key) {
        // Do something use Redis.
        return null;
    }
}

Upvotes: 1

Related Questions