Try to reopen Redis pub-sub connection on failure (#2430)

This commit is contained in:
Mark 2020-07-04 22:08:58 +03:00 committed by GitHub
parent 4514a17eaf
commit 6c7c1b67b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -63,14 +63,8 @@ public class RedisMessenger implements Messenger {
this.jedisPool = new JedisPool(new JedisPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, password, ssl);
this.plugin.getBootstrap().getScheduler().executeAsync(() -> {
this.sub = new Subscription(this);
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.subscribe(this.sub, CHANNEL);
} catch (Exception e) {
e.printStackTrace();
}
});
this.sub = new Subscription(this);
this.plugin.getBootstrap().getScheduler().executeAsync(sub);
}
@Override
@ -88,13 +82,42 @@ public class RedisMessenger implements Messenger {
this.jedisPool.destroy();
}
private static class Subscription extends JedisPubSub {
private static class Subscription extends JedisPubSub implements Runnable {
private final RedisMessenger parent;
private Subscription(RedisMessenger parent) {
this.parent = parent;
}
@Override
public void run() {
boolean wasBroken = false;
while (!Thread.interrupted() && !this.parent.jedisPool.isClosed()) {
try (Jedis jedis = this.parent.jedisPool.getResource()) {
if (wasBroken) {
parent.plugin.getLogger().info("Redis pubsub connection re-established");
wasBroken = false;
}
jedis.subscribe(this, CHANNEL);
} catch (Exception e) {
wasBroken = true;
parent.plugin.getLogger().warn("Redis pubsub connection dropped, trying to re-open the connection: " + e.getMessage());
try {
unsubscribe();
} catch (Exception ignored) {
}
// Sleep for 2 seconds to prevent massive spam in console
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
}
@Override
public void onMessage(String channel, String msg) {
if (!channel.equals(CHANNEL)) {