22
33import org .springframework .context .ApplicationContext ;
44
5+ import java .util .List ;
6+
57class DomainEventContext {
68
79 private static DomainEventContext instance ;
810 private ApplicationContext context ;
911
10-
1112 private DomainEventContext () {
12-
1313 }
1414
1515 public static DomainEventContext getInstance () {
@@ -23,37 +23,62 @@ public static DomainEventContext getInstance() {
2323 return instance ;
2424 }
2525
26- private void push (IEvent event , boolean sync ,boolean hasLoopEvent ) {
27- if (context != null ) {
28- String traceId = EventTraceContext .getInstance ().getOrCreateTrace ();
29- if (hasLoopEvent ){
30- EventTraceContext .getInstance ().clearTrace ();
31- traceId = EventTraceContext .getInstance ().getOrCreateTrace ();
32- }
33- EventTraceContext .getInstance ().addEvent (traceId ,event );
34- context .publishEvent (new DomainEvent (event , sync ,traceId ));
26+ private boolean isAsync (IEvent event ) {
27+ return event instanceof IAsyncEvent ;
28+ }
29+
30+ private void publish (IEvent event , String traceId ) {
31+ context .publishEvent (new DomainEvent (event , !isAsync (event ), traceId ));
32+ }
33+
34+ private void doPush (IEvent event , boolean hasLoopEvent ) {
35+ if (context == null ) {
36+ return ;
3537 }
38+ EventTraceContext traceContext = EventTraceContext .getInstance ();
39+ String traceId = hasLoopEvent
40+ ? traceContext .newTrace ()
41+ : traceContext .getOrCreateTrace ();
42+ traceContext .addEvent (traceId , event );
43+ publish (event , traceId );
3644 }
3745
3846 /**
39- * @param event
40- * @see EventPusher
41- * 默认 同步事件
47+ * 批量推送:整批事件共享同一 traceId,从而按顺序串行分发。
48+ * 批量内的同类事件不会被误判为循环调用(防环只针对 handler 内嵌套 push)。
4249 */
43- public void push (IEvent event ,boolean hasLoopEvent ) {
44- if (event instanceof IAsyncEvent ) {
45- this .push (event , false ,hasLoopEvent );
46- } else if (event instanceof ISyncEvent ) {
47- this .push (event , true ,hasLoopEvent );
48- } else {
49- this .push (event , true ,hasLoopEvent );
50+ void pushBatch (List <IEvent > events ) {
51+ if (context == null || events == null || events .isEmpty ()) {
52+ return ;
53+ }
54+ EventTraceContext traceContext = EventTraceContext .getInstance ();
55+ String previous = traceContext .getBatchTrace ();
56+ String traceId = traceContext .newTrace ();
57+ traceContext .setBatchTrace (traceId );
58+ try {
59+ for (IEvent event : events ) {
60+ traceContext .addEvent (traceId , event );
61+ publish (event , traceId );
62+ }
63+ } finally {
64+ if (previous == null ) {
65+ traceContext .clearBatchTrace ();
66+ } else {
67+ traceContext .setBatchTrace (previous );
68+ }
5069 }
5170 }
5271
72+ /**
73+ * 默认 同步事件
74+ *
75+ * @see EventPusher
76+ */
77+ public void push (IEvent event , boolean hasLoopEvent ) {
78+ doPush (event , hasLoopEvent );
79+ }
5380
5481 protected void initContext (ApplicationContext context ) {
5582 this .context = context ;
5683 }
57-
58-
5984}
0 commit comments