簡體   English   中英

使用 Java 中的 Azure Cosmos DB 發布/訂閱的示例

[英]Sample for publish/subscribe with Azure Cosmos DB in Java

我需要一個帶有 Azure Cosmos DB 的發布/訂閱事件消息系統。 我使用 Azure Cosmos DB Java SDK v4。

我嘗試使用基於此示例https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples/blob/main/src/main/java/com/azure/cosmos/examples的 ChangeFeedProcessor /changefeed/SampleChangeFeedProcessor.java但它不像預期的那樣工作。

我的問題:

  • 飼料收集/容器繼續增長。 在所有活動節點都收到事件后,如何刪除事件?
  • 事件的延遲似乎相對較大。 大約一分鍾。
  • 只有一個節點接收事件。 這對於負載平衡來說似乎很有趣,但這不是我的用例。

使用 Java SDK 的 4.12.0 版本,以下代碼對我有用。 但它使用來自驅動程序的測試代碼。 它可以在未來改變。

private static final String                CHANNEL = "events";

private CosmosContainer                    collection;

private boolean                            stopped;

void start( String clientID ) {
    CosmosContainerProperties props = new CosmosContainerProperties( CHANNEL, "/type" );
    // delete all events after 60 seconds. All nodes should receive it in the meantime.
    props.setDefaultTimeToLiveInSeconds( 60 );
    collection = getOrCreateContainer( props );
    Thread thread = new Thread( () -> {
        String[] continuation = new String[1];
        try {
            while( !stopped ) {
                // sample code: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosContainerChangeFeedTest.java
                CosmosChangeFeedRequestOptions options = continuation[0] == null ? //
                CosmosChangeFeedRequestOptions.createForProcessingFromNow( FeedRange.forFullRange() ) : // initial value
                CosmosChangeFeedRequestOptions.createForProcessingFromContinuation( continuation[0] ); // continue value
                Iterator<EventPOJO> it = collection //
                                .queryChangeFeed( options, EventPOJO.class ) //
                                .handle( ( response ) -> continuation[0] = response.getContinuationToken() ) //
                                .iterator();
                while( it.hasNext() ) {
                    EventPOJO event = it.next();
                    if( event.client != clientID ) {
                        // filter the own events
                        onMessage( event );
                    }
                }
                // poll interval
                Thread.sleep( 1000 );
            }
        } catch( Throwable th ) {
            if( !stopped ) {
                PersistenceLogger.LOGGER.error( th );
            }
        }
    }, CHANNEL );
    thread.setDaemon( true );
    thread.start();
}

<T> void send( T event, String clientID ) {
    EventPOJO evt = new EventPOJO();
    evt.id = ...
    evt.client = clientID;
    evt.type = event.getClass().getName();
    evt.message = ...

    collection.createItem( evt );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM