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
| @Slf4j @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}), @Signature(type = StatementHandler.class, method = "getBoundSql", args = {}), @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), }) @Component @RequiredArgsConstructor public class EventPublish implements Interceptor {
private final ApplicationEventPublisher applicationEventPublisher;
@Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = invocation.getArgs()[1]; Object returnValue = invocation.proceed(); BoundSql boundSql = mappedStatement.getBoundSql(parameter); String originalSql = boundSql.getSql(); DataSourceConfig.MYSQL_SOURCE_MAP.forEach((key, source) -> { try (Connection connection = source.getConnection()) { PreparedStatement prepareStatement = connection.prepareStatement(originalSql); DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql); handler.setParameters(prepareStatement); prepareStatement.executeUpdate(); } catch (SQLException e) { log.error("同步数据异常,数据源:{},错误信息", key, e); } }); return returnValue; }
@Override public Object plugin(Object target) { if (target instanceof Executor) { return Plugin.wrap(target, this); } return target; }
@Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); } }
|