1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
@Service @Slf4j public class CommonStrategyFactory {
private static final TwoLevelConcurrentHashMap<Class<? extends BaseCommonStrategy<?,?,?>>, Object,BaseCommonStrategy<?,?,?>> STRATEGY = new TwoLevelConcurrentHashMap<>();
@Autowired private void buildStrategyFactory(List<BaseCommonStrategy<?,?,?>> routes){ log.info("构建通用策略start:{}", routes.size()); routes.forEach(strategy->{ Class<? extends BaseCommonStrategy> aClass = strategy.getClass(); StrategyType annotation = AnnotationUtils.findAnnotation(aClass, StrategyType.class); if(null==annotation){ log.error("构建策略路由失败,找不到对应的annotation.clazz:{}", aClass); throw new GlobalException(ResponseCodeEnum.ANNOTATION_CAN_NOT_FIND); } STRATEGY.put(annotation.value(),strategy.routeKey(),strategy); }); }
public <P,K,R,S extends BaseCommonStrategy<P,K,R>> R handle(Class<? extends BaseCommonStrategy<P,K,R>> aClass,K routeKey,P parameters){ String simpleName = aClass.getSimpleName(); try{ BaseCommonStrategy<P, K, R> strategy = (BaseCommonStrategy<P, K, R>) STRATEGY.get(aClass, routeKey); if(null == strategy){ log.error("未找到对应的处理策略,routeKey:{},parameters:{}", routeKey, JSON.toJSON(parameters)); throw new GlobalException(ResponseCodeEnum.STARTEGY_CAN_NOT_FIND,simpleName+"未找到对应的处理策略"); } return strategy.handle(parameters); }catch (Exception e){ log.error("strategy handle occurs error:"+e); throw new GlobalException(e.getMessage()); } }
public static class TwoLevelConcurrentHashMap<K, R, P extends BaseCommonStrategy<?, ?, ?>> {
private ConcurrentHashMap<K, ConcurrentHashMap<R, P>> levelMap;
public TwoLevelConcurrentHashMap() { this.levelMap = new ConcurrentHashMap<>(); }
public void put(K k,R r,P p){ if(levelMap.containsKey(k)){ ConcurrentHashMap<R, P> rpConcurrentHashMap = levelMap.get(k); rpConcurrentHashMap.put(r,p); levelMap.put(k, rpConcurrentHashMap); return; } ConcurrentHashMap<R, P> hashMap = new ConcurrentHashMap<>(); hashMap.put(r,p); levelMap.put(k,hashMap); }
public P get(K aClass, R routeKey) { ConcurrentHashMap<R, P> rpConcurrentHashMap = levelMap.get(aClass); return rpConcurrentHashMap.get(routeKey); } } }
|