Skip to content

Instantly share code, notes, and snippets.

@boris1993
Last active September 21, 2018 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boris1993/c5a2da48dd740ca99a553a4c25af1a37 to your computer and use it in GitHub Desktop.
Save boris1993/c5a2da48dd740ca99a553a4c25af1a37 to your computer and use it in GitHub Desktop.
JedisFactory
/**
* This factory generates Jedis connection instances from a Jedis connection pool. <br>
* You can put your configurations in <code>redis.properties</code>, which accepts following properties:
* <ul>
* <li><code>redis.host</code> - Hostname or IP address to the Redis host. Default value is 127.0.0.1. </li>
* <li>(Optional) <code>redis.port</code> - Port of the Redis server. Default value is 6379. </li>
* <li>(Optional) <code>redis.timeout</code> - Connection timeout in seconds. Default value is 60. </li>
* <li>(Optional) <code>redis.auth</code> - Password for this Redis server. Default value is null. </li>
* </ul>
*
* @author Boris Zhao
*/
public class JedisFactory {
private static final String PROPERTY_KEY_HOST = "redis.host";
private static final String PROPERTY_KEY_PORT = "redis.port";
private static final String PROPERTY_KEY_TIMEOUT = "redis.timeout";
private static final String PROPERTY_KEY_AUTH = "redis.auth";
private static Logger logger = LoggerFactory.getLogger(JedisFactory.class);
private static JedisPool jedisPool = initJedisPool();
private JedisFactory() {
}
private static JedisPool initJedisPool() {
String host = "127.0.0.1";
int port = 6379;
int timeout = 60;
// Redis server will return an error when AUTH command is sent to server but no password is set
// So auth must be null when connecting with no password
String auth = null;
InputStream configFileInputStream = JedisFactory.class.getClassLoader().getResourceAsStream("redis.properties");
if (configFileInputStream != null) {
try {
Properties redisConnProperties = new Properties();
redisConnProperties.load(configFileInputStream);
host = redisConnProperties.getProperty(PROPERTY_KEY_HOST);
if (redisConnProperties.containsKey(PROPERTY_KEY_PORT)) {
port = Integer.parseInt(redisConnProperties.getProperty(PROPERTY_KEY_PORT));
}
if (redisConnProperties.containsKey(PROPERTY_KEY_TIMEOUT)) {
timeout = Integer.parseInt(redisConnProperties.getProperty(PROPERTY_KEY_TIMEOUT));
}
if (redisConnProperties.containsKey(PROPERTY_KEY_AUTH)) {
auth = redisConnProperties.getProperty(PROPERTY_KEY_AUTH);
}
} catch (IOException e) {
logger.warn("Failed to load redis.properties. Using default connection property. ");
}
} else {
logger.warn("redis.properties not found. Using default connection property. ");
}
return new JedisPool(new JedisPoolConfig(), host, port, timeout, auth);
}
public static Jedis getJedisConnInstance() {
return jedisPool.getResource();
}
}
redis.host=127.0.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment