20
20
import java .util .Collection ;
21
21
import java .util .List ;
22
22
import java .util .Map ;
23
+ import java .util .function .BiFunction ;
24
+ import java .util .stream .Collectors ;
23
25
import java .util .stream .IntStream ;
24
26
25
27
import org .springframework .amqp .core .Binding ;
28
30
import org .springframework .amqp .core .Declarables ;
29
31
import org .springframework .amqp .core .DirectExchange ;
30
32
import org .springframework .amqp .core .Queue ;
33
+ import org .springframework .util .Assert ;
31
34
32
35
/**
33
36
* Create Super Stream Topology {@link Declarable}s.
@@ -44,16 +47,33 @@ public class SuperStream extends Declarables {
44
47
* @param partitions the number of partitions.
45
48
*/
46
49
public SuperStream (String name , int partitions ) {
47
- super (declarables (name , partitions ));
50
+ this (name , partitions , (q , i ) -> IntStream .range (0 , i )
51
+ .mapToObj (String ::valueOf )
52
+ .collect (Collectors .toList ()));
48
53
}
49
54
50
- private static Collection <Declarable > declarables (String name , int partitions ) {
55
+ /**
56
+ * Create a Super Stream with the provided parameters.
57
+ * @param name the stream name.
58
+ * @param partitions the number of partitions.
59
+ * @param routingKeyStrategy a strategy to determine routing keys to use for the
60
+ * partitions. The first parameter is the queue name, the second the number of
61
+ * partitions, the returned list must have a size equal to the partitions.
62
+ */
63
+ public SuperStream (String name , int partitions , BiFunction <String , Integer , List <String >> routingKeyStrategy ) {
64
+ super (declarables (name , partitions , routingKeyStrategy ));
65
+ }
66
+
67
+ private static Collection <Declarable > declarables (String name , int partitions ,
68
+ BiFunction <String , Integer , List <String >> routingKeyStrategy ) {
69
+
51
70
List <Declarable > declarables = new ArrayList <>();
52
- String [] rks = IntStream .range (0 , partitions ).mapToObj (String ::valueOf ).toArray (String []::new );
71
+ List <String > rks = routingKeyStrategy .apply (name , partitions );
72
+ Assert .state (rks .size () == partitions , () -> "Expected " + partitions + " routing keys, not " + rks .size ());
53
73
declarables .add (new DirectExchange (name , true , false , Map .of ("x-super-stream" , true )));
54
74
for (int i = 0 ; i < partitions ; i ++) {
55
- String rk = rks [ i ] ;
56
- Queue q = new Queue (name + "-" + rk , true , false , false , Map .of ("x-queue-type" , "stream" ));
75
+ String rk = rks . get ( i ) ;
76
+ Queue q = new Queue (name + "-" + i , true , false , false , Map .of ("x-queue-type" , "stream" ));
57
77
declarables .add (q );
58
78
declarables .add (new Binding (q .getName (), DestinationType .QUEUE , name , rk ,
59
79
Map .of ("x-stream-partition-order" , i )));
0 commit comments