唯一id
自定义注解+mybatis的自定义拦截器+雪花算法解决自定义唯一id
自定义注解
1 2 3 4 5 6 7 8 9 10 11 12
| @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AutoId { AutoId.IdType value() default AutoId.IdType.SNOWFLAKE; public static enum IdType { UUID, SNOWFLAKE; private IdType() { } } }
|
自定义拦截器
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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
| @Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }), }) public class AutoIdInterceptor implements Interceptor { private int workerId; private int dataCenterId; public AutoIdInterceptor(int workerId, int dataCenterId) { this.workerId = workerId; this.dataCenterId = dataCenterId; }
private Map<Class<?>, List<Handler>> handlerMap = new ConcurrentHashMap<>(); @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Object entity = args[1]; if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) { Set<Object> entitySet = getEntitySet(entity); for (Object object : entitySet) { process(object); } } return invocation.proceed(); }
private Set<Object> getEntitySet(Object object) { Set<Object> set = new HashSet<>(); if (object instanceof Map) {
Map<String, Object> map = (Map<String, Object>) object; map.forEach((key, value) -> { if (value instanceof Collection) { set.addAll((Collection) value); } else { set.add(value); } });
} else { set.add(object); } return set; }
private void process(Object object) throws Exception { Class<?> handlerKey = object.getClass(); List<Handler> handlerList = handlerMap.get(handlerKey); sync: if (handlerList == null || handlerList.isEmpty()) { synchronized (this) { handlerList = handlerMap.get(handlerKey); if (handlerList != null && !handlerList.isEmpty()) { break sync; } handlerMap.put(handlerKey, handlerList = new ArrayList<>()); Class<?> cls = object.getClass(); List<Field> idFields = getIdFields(cls); Class<?> superClass = cls.getSuperclass(); if (superClass != null && !superClass.equals(Object.class)) { idFields.addAll(getIdFields(superClass)); Class<?> doubleSuperClass = superClass.getSuperclass(); if (!doubleSuperClass.equals(Object.class)) { idFields.addAll(getIdFields(doubleSuperClass)); } } if (idFields != null && !idFields.isEmpty()) { for (Field idField : idFields) { AutoId annotation = idField.getAnnotation(AutoId.class); if (idField.getType().isAssignableFrom(String.class)) { if (annotation.value().equals(AutoId.IdType.UUID)) { handlerList.add(new UUIDHandler(idField)); } else if (annotation.value().equals(AutoId.IdType.SNOWFLAKE)) { handlerList.add(new UniqueLongHexHandler(idField, new SnowflakeIdWorker(workerId, dataCenterId))); } } else if (idField.getType().isAssignableFrom(Long.class)) { if (annotation.value().equals(AutoId.IdType.SNOWFLAKE)) { handlerList.add(new UniqueLongHandler(idField, new SnowflakeIdWorker(workerId, dataCenterId))); } } } } } } for (Handler handler : handlerList) { handler.accept(object); } }
private List<Field> getIdFields(Class<?> clazz) { Field[] allFields = clazz.getDeclaredFields(); return Arrays.stream(allFields).filter(field -> field.getAnnotation(AutoId.class) != null).collect(Collectors.toList()); }
private static abstract class Handler { Field field;
Handler(Field field) { this.field = field; } abstract void handle(Field field, Object object) throws Exception;
private boolean checkField(Object object, Field field) throws IllegalAccessException { if (!field.isAccessible()) { field.setAccessible(true); } return field.get(object) == null; }
public void accept(Object o) throws Exception { if (checkField(o, field)) { handle(field, o); } } }
private static class UUIDHandler extends Handler { UUIDHandler(Field field) { super(field); }
@Override void handle(Field field, Object object) throws Exception { field.set(object, UUID.randomUUID().toString().replace("-", "")); } }
private static class UniqueLongHandler extends Handler { private SnowflakeIdWorker idWorker; UniqueLongHandler(Field field, SnowflakeIdWorker idWorker) { super(field); this.idWorker = idWorker; }
@Override void handle(Field field, Object object) throws Exception { field.set(object, idWorker.nextId()); } }
private static class UniqueLongHexHandler extends Handler { private SnowflakeIdWorker idWorker; UniqueLongHexHandler(Field field, SnowflakeIdWorker idWorker) { super(field); this.idWorker = idWorker; }
@Override void handle(Field field, Object object) throws Exception { field.set(object, String.valueOf(idWorker.nextId())); } } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } }
|