Reputation: 20450
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
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
Reputation: 3320
Have a look at how we are using Jedis:
Create a singleton org.springframework.data.redis.connection.jedis.JedisConnectionFactory
instance by passing host and port info
Create singleton org.springframework.data.redis.core.RedisTemplate
instance by passing the connection factory to it
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