@ -1,9 +1,7 @@
package me.william278.husksync.redis ;
import me.william278.husksync.Settings ;
import redis.clients.jedis.Jedis ;
import redis.clients.jedis.JedisClientConfig ;
import redis.clients.jedis.JedisPubSub ;
import redis.clients.jedis.* ;
import redis.clients.jedis.exceptions.JedisException ;
import java.io.IOException ;
@ -16,6 +14,18 @@ public abstract class RedisListener {
* /
public boolean isActiveAndEnabled ;
/ * *
* Pool of connections to the Redis server
* /
private static JedisPool jedisPool ;
/ * *
* Creates a new RedisListener and initialises the Redis connection
* /
public RedisListener ( ) {
jedisPool = new JedisPool ( new JedisPoolConfig ( ) , Settings . redisHost , Settings . redisPort ) ;
}
/ * *
* Handle an incoming { @link RedisMessage }
*
@ -31,20 +41,34 @@ public abstract class RedisListener {
* /
public abstract void log ( Level level , String message ) ;
/ * *
* Fetch a connection to the Redis server from the JedisPool
*
* @return Jedis instance from the pool
* /
public static Jedis getJedisConnection ( ) {
return jedisPool . getResource ( ) ;
}
/ * *
* Start the Redis listener
* /
public final void listen ( ) {
try ( Jedis jedis = new Jedis ( Settings . redisHost , Settings . redisPort ) ) {
final String jedisPassword = Settings . redisPassword ;
jedis . connect ( ) ;
if ( jedis . isConnected ( ) ) {
new Thread ( ( ) - > {
try ( Jedis jedis = getJedisConnection ( ) ) {
if ( ! jedisPassword . equals ( "" ) ) {
jedis . auth ( jedisPassword ) ;
}
if ( jedis . isConnected ( ) ) {
isActiveAndEnabled = true ;
log ( Level . INFO , "Enabled Redis listener successfully!" ) ;
new Thread ( ( ) - > jedis . subscribe ( new JedisPubSub ( ) {
} else {
isActiveAndEnabled = false ;
log ( Level . SEVERE , "Connection to the Redis server could not be established, please check the credentials." ) ;
return ;
}
jedis . subscribe ( new JedisPubSub ( ) {
@Override
public void onMessage ( String channel , String message ) {
// Only accept messages to the HuskSync channel
@ -59,13 +83,11 @@ public abstract class RedisListener {
log ( Level . SEVERE , "Failed to deserialize message target" ) ;
}
}
} , RedisMessage . REDIS_CHANNEL ) , "Redis Subscriber" ) . start ( ) ;
} else {
} , RedisMessage . REDIS_CHANNEL ) ;
} catch ( JedisException | IllegalStateException e ) {
log ( Level . SEVERE , "An exception occurred with the Jedis Subscriber!" ) ;
isActiveAndEnabled = false ;
log ( Level . SEVERE , "Failed to initialize the redis listener!" ) ;
}
} catch ( JedisException e ) {
log ( Level . SEVERE , "Failed to establish a connection to the Redis server!" ) ;
}
} , "Redis Subscriber" ) . start ( ) ;
}
}