9
9
import java .io .IOException ;
10
10
import java .util .Base64 ;
11
11
import java .util .Locale ;
12
+ import java .util .UUID ;
13
+ import java .util .function .Consumer ;
12
14
import java .util .logging .Logger ;
13
15
14
16
public class RedisTransport implements RpcTransport {
@@ -18,6 +20,8 @@ public class RedisTransport implements RpcTransport {
18
20
private final JedisPool jedisPool ;
19
21
private final String topic ;
20
22
private RedisSubscriptionThread redisSubscriptionThread ;
23
+ private final UUID transportId = UUID .randomUUID ();
24
+ private boolean ignoreSelf = true ;
21
25
22
26
public RedisTransport (JedisPool jedisPool , String topic ) {
23
27
this .jedisPool = jedisPool ;
@@ -34,14 +38,22 @@ public RedisTransport(String host, int port, String topic) {
34
38
this .topic = topic ;
35
39
}
36
40
41
+ public RedisTransport withIgnoreSelf (boolean ignoreSelf ) {
42
+ this .ignoreSelf = ignoreSelf ;
43
+ return this ;
44
+ }
45
+
37
46
@ Override
38
47
public void send (Direction direction , byte [] bytes ) {
39
48
if (jedisPool .isClosed ()) {
40
49
throw new IllegalStateException ("Jedis pool is closed" );
41
50
}
42
51
43
52
try (Jedis connection = jedisPool .getResource ()) {
44
- connection .publish (getTopicName (direction ), Base64 .getEncoder ().encodeToString (bytes ));
53
+ connection .publish (
54
+ getTopicName (direction ),
55
+ transportId + Base64 .getEncoder ().encodeToString (bytes )
56
+ );
45
57
}
46
58
}
47
59
@@ -51,11 +63,31 @@ public void subscribe(Direction direction, SubscriptionHandler onReceive) {
51
63
throw new IllegalStateException ("Jedis pool is closed" );
52
64
}
53
65
66
+ StringMessageBroker wrappedHandler = (message ) -> {
67
+ byte [] bytes = message .getBytes ();
68
+ // only split after UUID, which always has a length of 36
69
+ byte [] uuid = new byte [36 ];
70
+ System .arraycopy (bytes , 0 , uuid , 0 , 36 );
71
+
72
+ if (ignoreSelf && transportId .toString ().equals (new String (uuid ))) {
73
+ return false ;
74
+ }
75
+
76
+ byte [] data = new byte [bytes .length - 36 ];
77
+ System .arraycopy (bytes , 36 , data , 0 , data .length );
78
+
79
+ try {
80
+ return onReceive .onPacket (Base64 .getDecoder ().decode (data ));
81
+ } catch (Exception e ) {
82
+ throw new RuntimeException (e );
83
+ }
84
+ };
85
+
54
86
if (redisSubscriptionThread == null ) {
55
- redisSubscriptionThread = new RedisSubscriptionThread (onReceive , logger , getTopicName (direction ), jedisPool );
87
+ redisSubscriptionThread = new RedisSubscriptionThread (wrappedHandler , logger , getTopicName (direction ), jedisPool );
56
88
redisSubscriptionThread .start ().join ();
57
89
} else {
58
- redisSubscriptionThread .subscribe (getTopicName (direction ), onReceive );
90
+ redisSubscriptionThread .subscribe (getTopicName (direction ), wrappedHandler );
59
91
}
60
92
}
61
93
0 commit comments