|
| 1 | +package com.codingapi.springboot.framework.event; |
| 2 | + |
| 3 | +import com.codingapi.springboot.framework.exception.EventLoopException; |
| 4 | +import com.codingapi.springboot.framework.utils.RandomGenerator; |
| 5 | +import lombok.Getter; |
| 6 | + |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +/** |
| 10 | + * 事件跟踪上下文 |
| 11 | + */ |
| 12 | +public class EventTraceContext { |
| 13 | + |
| 14 | + @Getter |
| 15 | + private final static EventTraceContext instance = new EventTraceContext(); |
| 16 | + |
| 17 | + // trace key |
| 18 | + private final Set<String> traceKeys = new HashSet<>(); |
| 19 | + |
| 20 | + // thread local |
| 21 | + private final ThreadLocal<String> threadLocal = new ThreadLocal<>(); |
| 22 | + |
| 23 | + // event listenerKey state |
| 24 | + private final Map<String, Boolean> eventKeyState = new HashMap<>(); |
| 25 | + |
| 26 | + |
| 27 | + private EventTraceContext() { |
| 28 | + } |
| 29 | + |
| 30 | + String getOrCreateTrace() { |
| 31 | + String eventKey = threadLocal.get(); |
| 32 | + if (eventKey != null) { |
| 33 | + return eventKey.split("#")[0]; |
| 34 | + } |
| 35 | + String traceId = UUID.randomUUID().toString().replaceAll("-", ""); |
| 36 | + traceKeys.add(traceId); |
| 37 | + return traceId; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * get event key |
| 42 | + * traceId = eventKey.split("#")[0] |
| 43 | + */ |
| 44 | + public String getEventKey() { |
| 45 | + return threadLocal.get(); |
| 46 | + } |
| 47 | + |
| 48 | + void createEventKey(String traceId) { |
| 49 | + String eventKey = traceId + "#" + RandomGenerator.randomString(8); |
| 50 | + eventKeyState.put(eventKey, false); |
| 51 | + threadLocal.set(eventKey); |
| 52 | + } |
| 53 | + |
| 54 | + void checkEventState() { |
| 55 | + String eventKey = threadLocal.get(); |
| 56 | + if (eventKey != null) { |
| 57 | + boolean state = eventKeyState.get(eventKey); |
| 58 | + if (!state) { |
| 59 | + // event execute finish |
| 60 | + String traceId = eventKey.split("#")[0]; |
| 61 | + traceKeys.remove(traceId); |
| 62 | + EventStackContext.getInstance().remove(traceId); |
| 63 | + } |
| 64 | + eventKeyState.remove(eventKey); |
| 65 | + } |
| 66 | + threadLocal.remove(); |
| 67 | + } |
| 68 | + |
| 69 | + void addEvent(String traceId, IEvent event) { |
| 70 | + boolean hasEventLoop = EventStackContext.getInstance().checkEventLoop(traceId, event); |
| 71 | + if (hasEventLoop) { |
| 72 | + List<Class<?>> stack = EventStackContext.getInstance().getEventClasses(traceId); |
| 73 | + traceKeys.remove(traceId); |
| 74 | + EventStackContext.getInstance().remove(traceId); |
| 75 | + eventKeyState.remove(traceId); |
| 76 | + threadLocal.remove(); |
| 77 | + throw new EventLoopException(stack, event); |
| 78 | + } |
| 79 | + EventStackContext.getInstance().addEvent(traceId, event); |
| 80 | + } |
| 81 | +} |
0 commit comments