@@ -9,32 +9,49 @@ public abstract class RedisHandler {
99 private final JedisPool subscribePool ;
1010
1111 public RedisHandler (String host , int port , String username , String password ) {
12- int timeout = 2000 ; // Set a reasonable timeout
13- if (username .isEmpty () && password .isEmpty ()) {
14- publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout );
15- subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout );
16- } else if (username .isEmpty ()) {
17- publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout , password );
18- subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout , password );
19- } else {
20- publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout , username , password );
21- subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout , username , password );
22- }
12+ int timeout = 2000 ; // Set a reasonable timeout
13+ if (username .isEmpty () && password .isEmpty ()) {
14+ publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout );
15+ subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout );
16+ } else if (username .isEmpty ()) {
17+ publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout , password );
18+ subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout , password );
19+ } else {
20+ publishPool = new JedisPool (new JedisPoolConfig (), host , port , timeout , username , password );
21+ subscribePool = new JedisPool (new JedisPoolConfig (), host , port , timeout , username , password );
22+ }
2323 }
2424
2525 public void close () {
26+ try {
27+ if (subscribeThread != null && subscribeThread .isAlive ()) {
28+ subscribeThread .interrupt (); // Signal the thread to stop
29+ }
30+ } catch (Exception e ) {
31+ debug ("Failed to interrupt Redis subscribe thread: " + e .getMessage ());
32+ }
33+
34+
2635 publishPool .close ();
2736 subscribePool .close ();
2837 }
2938
30- public abstract void debug ( String message ) ;
39+ private Thread subscribeThread ;
3140
3241 public void loadListener (RedisListener listener ) {
33- try (Jedis jedis = subscribePool .getResource ()) {
34- jedis .subscribe (listener , listener .getChannel ());
35- }
42+ subscribeThread = new Thread (() -> {
43+ try (Jedis jedis = subscribePool .getResource ()) {
44+ jedis .subscribe (listener , listener .getChannel ());
45+ } catch (Exception e ) {
46+ debug ("Redis subscribe error: " + e .getMessage ());
47+ }
48+ }, "RedisSubscribeThread" );
49+
50+ subscribeThread .start ();
3651 }
3752
53+ public abstract void debug (String message );
54+
3855 protected abstract void onMessage (String channel , String [] message );
3956
4057 public void sendMessage (String channel , String ... message ) {
0 commit comments