如何解决使用 Java 中的 Azure Cosmos DB 进行发布/订阅的示例
我需要一个带有 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/changefeed/SampleChangeFeedProcessor.java 的 ChangeFeedProcessor,但它没有按预期工作。
我的问题:
解决方法
在 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 );
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。