Use a continuous connection for pub/sub to avoid EndOfStreamException and increase exception logging verbosity

feat/data-edit-commands
William 3 years ago
parent 4ab5070043
commit 9bf0fe7bb9

@ -2,6 +2,7 @@ package me.william278.husksync.redis;
import me.william278.husksync.Settings; import me.william278.husksync.Settings;
import redis.clients.jedis.*; import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisException;
import java.io.IOException; import java.io.IOException;
@ -68,19 +69,28 @@ public abstract class RedisListener {
*/ */
public final void listen() { public final void listen() {
new Thread(() -> { new Thread(() -> {
try (Jedis jedis = getJedisConnection()) {
if (jedis.isConnected()) {
isActiveAndEnabled = true; isActiveAndEnabled = true;
log(Level.INFO, "Enabled Redis listener successfully!"); while (isActiveAndEnabled) {
Jedis subscriber;
if (Settings.redisPassword.isEmpty()) {
subscriber = new Jedis(Settings.redisHost,
Settings.redisPort,
0);
} else { } else {
isActiveAndEnabled = false; final JedisClientConfig config = DefaultJedisClientConfig.builder()
log(Level.SEVERE, """ .password(Settings.redisPassword)
Failed to establish connection to the Redis server. .timeoutMillis(0).build();
HuskSync will now abort initialization.
Please check the credentials are correct and restart your server."""); subscriber = new Jedis(Settings.redisHost,
return; Settings.redisPort,
config);
} }
jedis.subscribe(new JedisPubSub() { subscriber.connect();
log(Level.INFO, "Enabled Redis listener successfully!");
try {
subscriber.subscribe(new JedisPubSub() {
@Override @Override
public void onMessage(String channel, String message) { public void onMessage(String channel, String message) {
// Only accept messages to the HuskSync channel // Only accept messages to the HuskSync channel
@ -96,9 +106,16 @@ public abstract class RedisListener {
} }
} }
}, RedisMessage.REDIS_CHANNEL); }, RedisMessage.REDIS_CHANNEL);
} catch (JedisException | IllegalStateException e) { } catch (JedisConnectionException connectionException) {
log(Level.SEVERE, "An exception occurred with the Jedis Subscriber!"); log(Level.SEVERE, "A connection exception occurred with the Jedis listener");
connectionException.printStackTrace();
} catch (JedisException jedisException) {
isActiveAndEnabled = false; isActiveAndEnabled = false;
log(Level.SEVERE, "An exception occurred with the Jedis listener");
jedisException.printStackTrace();
} finally {
subscriber.close();
}
} }
}, "Redis Subscriber").start(); }, "Redis Subscriber").start();
} }

Loading…
Cancel
Save