Search in sources :

Example 1 with AllowConcurrentEvents

use of com.google.common.eventbus.AllowConcurrentEvents in project sharding-jdbc by dangdangdotcom.

the class BestEffortsDeliveryListener method listen.

@Subscribe
@AllowConcurrentEvents
public void listen(final DMLExecutionEvent event) {
    if (!isProcessContinuously()) {
        return;
    }
    SoftTransactionConfiguration transactionConfig = SoftTransactionManager.getCurrentTransactionConfiguration().get();
    TransactionLogStorage transactionLogStorage = TransactionLogStorageFactory.createTransactionLogStorage(transactionConfig.buildTransactionLogDataSource());
    BEDSoftTransaction bedSoftTransaction = (BEDSoftTransaction) SoftTransactionManager.getCurrentTransaction().get();
    switch(event.getEventExecutionType()) {
        case BEFORE_EXECUTE:
            //TODO 对于批量执行的SQL需要解析成两层列表
            transactionLogStorage.add(new TransactionLog(event.getId(), bedSoftTransaction.getTransactionId(), bedSoftTransaction.getTransactionType(), event.getDataSource(), event.getSql(), event.getParameters(), System.currentTimeMillis(), 0));
            return;
        case EXECUTE_SUCCESS:
            transactionLogStorage.remove(event.getId());
            return;
        case EXECUTE_FAILURE:
            boolean deliverySuccess = false;
            for (int i = 0; i < transactionConfig.getSyncMaxDeliveryTryTimes(); i++) {
                if (deliverySuccess) {
                    return;
                }
                boolean isNewConnection = false;
                Connection conn = null;
                PreparedStatement preparedStatement = null;
                try {
                    conn = bedSoftTransaction.getConnection().getConnection(event.getDataSource(), SQLStatementType.UPDATE);
                    if (!isValidConnection(conn)) {
                        bedSoftTransaction.getConnection().releaseBrokenConnection(conn);
                        conn = bedSoftTransaction.getConnection().getConnection(event.getDataSource(), SQLStatementType.UPDATE);
                        isNewConnection = true;
                    }
                    preparedStatement = conn.prepareStatement(event.getSql());
                    //TODO 对于批量事件需要解析成两层列表
                    for (int parameterIndex = 0; parameterIndex < event.getParameters().size(); parameterIndex++) {
                        preparedStatement.setObject(parameterIndex + 1, event.getParameters().get(parameterIndex));
                    }
                    preparedStatement.executeUpdate();
                    deliverySuccess = true;
                    transactionLogStorage.remove(event.getId());
                } catch (final SQLException ex) {
                    log.error(String.format("Delivery times %s error, max try times is %s", i + 1, transactionConfig.getSyncMaxDeliveryTryTimes()), ex);
                } finally {
                    close(isNewConnection, conn, preparedStatement);
                }
            }
            return;
        default:
            throw new UnsupportedOperationException(event.getEventExecutionType().toString());
    }
}
Also used : TransactionLog(com.dangdang.ddframe.rdb.transaction.soft.storage.TransactionLog) SQLException(java.sql.SQLException) TransactionLogStorage(com.dangdang.ddframe.rdb.transaction.soft.storage.TransactionLogStorage) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) BEDSoftTransaction(com.dangdang.ddframe.rdb.transaction.soft.bed.BEDSoftTransaction) SoftTransactionConfiguration(com.dangdang.ddframe.rdb.transaction.soft.api.config.SoftTransactionConfiguration) AllowConcurrentEvents(com.google.common.eventbus.AllowConcurrentEvents) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with AllowConcurrentEvents

use of com.google.common.eventbus.AllowConcurrentEvents in project killbill by killbill.

the class PushNotificationListener method triggerPushNotifications.

@AllowConcurrentEvents
@Subscribe
public void triggerPushNotifications(final ExtBusEvent event) {
    final TenantContext context = contextFactory.createTenantContext(event.getTenantId());
    try {
        final List<String> callbacks = getCallbacksForTenant(context);
        if (callbacks.isEmpty()) {
            // Optimization - see https://github.com/killbill/killbill/issues/297
            return;
        }
        dispatchCallback(event.getTenantId(), event, callbacks);
    } catch (final TenantApiException e) {
        log.warn("Failed to retrieve push notification callback for tenant {}", event.getTenantId());
    } catch (final IOException e) {
        log.warn("Failed to retrieve push notification callback for tenant {}", event.getTenantId());
    }
}
Also used : TenantApiException(org.killbill.billing.tenant.api.TenantApiException) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) TenantContext(org.killbill.billing.util.callcontext.TenantContext) IOException(java.io.IOException) AllowConcurrentEvents(com.google.common.eventbus.AllowConcurrentEvents) Subscribe(com.google.common.eventbus.Subscribe)

Example 3 with AllowConcurrentEvents

use of com.google.common.eventbus.AllowConcurrentEvents in project bazel by bazelbuild.

the class AggregatingTestListener method populateTests.

/**
   * Populates the test summary map as soon as test filtering is complete.
   * This is the earliest at which the final set of targets to test is known.
   */
@Subscribe
@AllowConcurrentEvents
public void populateTests(TestFilteringCompleteEvent event) {
    // Add all target runs to the map, assuming 1:1 status artifact <-> result.
    synchronized (summaryLock) {
        for (ConfiguredTarget target : event.getTestTargets()) {
            Iterable<Artifact> statusArtifacts = target.getProvider(TestProvider.class).getTestParams().getTestStatusArtifacts();
            preconditionHelper.checkState(remainingRuns.putAll(asKey(target), statusArtifacts));
            // And create an empty summary suitable for incremental analysis.
            // Also has the nice side effect of mapping labels to RuleConfiguredTargets.
            TestSummary.Builder summary = TestSummary.newBuilder().setTarget(target).setStatus(BlazeTestStatus.NO_STATUS);
            preconditionHelper.checkState(summaries.put(asKey(target), summary) == null);
        }
    }
}
Also used : ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) Artifact(com.google.devtools.build.lib.actions.Artifact) AllowConcurrentEvents(com.google.common.eventbus.AllowConcurrentEvents) Subscribe(com.google.common.eventbus.Subscribe)

Example 4 with AllowConcurrentEvents

use of com.google.common.eventbus.AllowConcurrentEvents in project bazel by bazelbuild.

the class AggregatingTestListener method testEvent.

/**
   * Records a new test run result and incrementally updates the target status.
   * This event is sent upon completion of executed test runs.
   */
@Subscribe
@AllowConcurrentEvents
public void testEvent(TestResult result) {
    Preconditions.checkState(statusMap.put(result.getTestStatusArtifact(), result) == null, "Duplicate result reported for an individual test shard");
    ActionOwner testOwner = result.getTestAction().getOwner();
    LabelAndConfiguration targetLabel = LabelAndConfiguration.of(testOwner.getLabel(), result.getTestAction().getConfiguration());
    // executed. Hence report that fact as a cached attempt.
    if (result.isCached()) {
        eventBus.post(TestAttempt.fromCachedTestResult(result));
    }
    TestSummary finalTestSummary = null;
    synchronized (summaryLock) {
        TestSummary.Builder summary = summaries.get(targetLabel);
        preconditionHelper.checkNotNull(summary);
        if (!remainingRuns.remove(targetLabel, result.getTestStatusArtifact())) {
            // This situation is likely to happen if --notest_keep_going is set with multiple targets.
            return;
        }
        summary = analyzer.incrementalAnalyze(summary, result);
        // If all runs are processed, the target is finished and ready to report.
        if (!remainingRuns.containsKey(targetLabel)) {
            finalTestSummary = summary.build();
        }
    }
    // Report finished targets.
    if (finalTestSummary != null) {
        eventBus.post(finalTestSummary);
    }
}
Also used : LabelAndConfiguration(com.google.devtools.build.lib.analysis.LabelAndConfiguration) ActionOwner(com.google.devtools.build.lib.actions.ActionOwner) AllowConcurrentEvents(com.google.common.eventbus.AllowConcurrentEvents) Subscribe(com.google.common.eventbus.Subscribe)

Example 5 with AllowConcurrentEvents

use of com.google.common.eventbus.AllowConcurrentEvents in project sharding-jdbc by dangdangdotcom.

the class ShardingPreparedStatementTest method assertAddBatch.

@Test
public void assertAddBatch() throws SQLException {
    DMLExecutionEventBus.register(new DMLExecutionEventListener() {

        private List<DMLExecutionEvent> beforeEvents = new ArrayList<>();

        @Override
        public String getName() {
            return "test";
        }

        @Subscribe
        @AllowConcurrentEvents
        public void subscribe(final DMLExecutionEvent event) {
            assertTrue(event.isBatch());
            assertThat(event.getBatchParameters().size(), is(2));
            if (event.getEventExecutionType().equals(EventExecutionType.BEFORE_EXECUTE)) {
                beforeEvents.add(event);
            } else if (event.getEventExecutionType().equals(EventExecutionType.EXECUTE_SUCCESS)) {
                assertThat(beforeEvents, hasItem(event));
            }
        }
    });
    String sql = "INSERT INTO `t_order`(`order_id`, `user_id`, `status`) VALUES (?,?,?)";
    try (Connection connection = shardingDataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
        preparedStatement.setInt(1, 3101);
        preparedStatement.setInt(2, 11);
        preparedStatement.setString(3, "BATCH");
        preparedStatement.addBatch();
        preparedStatement.setInt(1, 3102);
        preparedStatement.setInt(2, 12);
        preparedStatement.setString(3, "BATCH");
        preparedStatement.addBatch();
        preparedStatement.setInt(1, 3111);
        preparedStatement.setInt(2, 21);
        preparedStatement.setString(3, "BATCH");
        preparedStatement.addBatch();
        preparedStatement.setInt(1, 3112);
        preparedStatement.setInt(2, 22);
        preparedStatement.setString(3, "BATCH");
        preparedStatement.addBatch();
        int[] result = preparedStatement.executeBatch();
        for (int each : result) {
            assertThat(each, is(1));
        }
    } finally {
        DMLExecutionEventBus.clearListener();
    }
}
Also used : DMLExecutionEvent(com.dangdang.ddframe.rdb.sharding.executor.event.DMLExecutionEvent) AllowConcurrentEvents(com.google.common.eventbus.AllowConcurrentEvents) DMLExecutionEventListener(com.dangdang.ddframe.rdb.sharding.executor.event.DMLExecutionEventListener) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Subscribe(com.google.common.eventbus.Subscribe) Test(org.junit.Test) AbstractShardingDataBasesOnlyDBUnitTest(com.dangdang.ddframe.rdb.integrate.db.AbstractShardingDataBasesOnlyDBUnitTest)

Aggregations

AllowConcurrentEvents (com.google.common.eventbus.AllowConcurrentEvents)13 Subscribe (com.google.common.eventbus.Subscribe)13 InternalCallContext (org.killbill.billing.callcontext.InternalCallContext)7 UUID (java.util.UUID)4 AccountApiException (org.killbill.billing.account.api.AccountApiException)4 InvoiceApiException (org.killbill.billing.invoice.api.InvoiceApiException)4 Account (org.killbill.billing.account.api.Account)3 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ArrayList (java.util.ArrayList)2 AbstractShardingDataBasesOnlyDBUnitTest (com.dangdang.ddframe.rdb.integrate.db.AbstractShardingDataBasesOnlyDBUnitTest)1 DMLExecutionEvent (com.dangdang.ddframe.rdb.sharding.executor.event.DMLExecutionEvent)1 DMLExecutionEventListener (com.dangdang.ddframe.rdb.sharding.executor.event.DMLExecutionEventListener)1 SoftTransactionConfiguration (com.dangdang.ddframe.rdb.transaction.soft.api.config.SoftTransactionConfiguration)1 BEDSoftTransaction (com.dangdang.ddframe.rdb.transaction.soft.bed.BEDSoftTransaction)1 TransactionLog (com.dangdang.ddframe.rdb.transaction.soft.storage.TransactionLog)1 TransactionLogStorage (com.dangdang.ddframe.rdb.transaction.soft.storage.TransactionLogStorage)1 ActionOwner (com.google.devtools.build.lib.actions.ActionOwner)1 Artifact (com.google.devtools.build.lib.actions.Artifact)1 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)1