io.etcd.jetcd.Watch Java Examples

The following examples show how to use io.etcd.jetcd.Watch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Main.java    From jetcd with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    Args cmd = new Args();

    JCommander.newBuilder().addObject(cmd).build().parse(args);

    CountDownLatch latch = new CountDownLatch(cmd.maxEvents);
    ByteSequence key = ByteSequence.from(cmd.key, StandardCharsets.UTF_8);
    Collection<URI> endpoints = Util.toURIs(cmd.endpoints);

    Watch.Listener listener = Watch.listener(response -> {
        LOGGER.info("Watching for key={}", cmd.key);

        for (WatchEvent event : response.getEvents()) {
            LOGGER.info("type={}, key={}, value={}", event.getEventType(),
                Optional.ofNullable(event.getKeyValue().getKey()).map(bs -> bs.toString(StandardCharsets.UTF_8)).orElse(""),
                Optional.ofNullable(event.getKeyValue().getValue()).map(bs -> bs.toString(StandardCharsets.UTF_8))
                    .orElse(""));
        }

        latch.countDown();
    });

    try (Client client = Client.builder().endpoints(endpoints).build();
        Watch watch = client.getWatchClient();
        Watch.Watcher watcher = watch.watch(key, listener)) {

        latch.await();
    } catch (Exception e) {
        LOGGER.error("Watching Error {}", e);
        System.exit(1);
    }
}
 
Example #2
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ClusterBooking booking) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    EtcdClusterBooking etcdBooking = (EtcdClusterBooking) booking;
    //先查询
    ByteSequence key = ByteSequence.from(etcdBooking.getPath(), UTF_8);
    //先查询,无异常后添加watcher,若结果不为空,通知FULL事件
    GetOption getOption = GetOption.newBuilder().withPrefix(key).build();
    client.getKVClient().get(key, getOption).whenComplete((res, err) -> {
        if (!isOpen()) {
            future.completeExceptionally(new IllegalStateException("controller is closed."));
        } else if (err != null) {
            logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getService(), err.getMessage()), err);
            future.completeExceptionally(err);
        } else {
            List<WatchEvent> events = new ArrayList<>();
            res.getKvs().forEach(kv -> events.add(new WatchEvent(kv, null, PUT)));
            etcdBooking.onUpdate(events, res.getHeader().getRevision(), FULL);
            //添加watch
            try {
                WatchOption watchOption = WatchOption.newBuilder().withPrefix(key).build();
                Watch.Watcher watcher = client.getWatchClient().watch(key, watchOption, etcdBooking);
                etcdBooking.setWatcher(watcher);
                future.complete(null);
            } catch (Exception e) {
                logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getService(), e.getMessage()), e);
                future.completeExceptionally(e);
            }
        }
    });
    return future;
}
 
Example #3
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doUnsubscribe(final ClusterBooking booking) {
    EtcdClusterBooking etcdBooking = (EtcdClusterBooking) booking;
    Watch.Watcher watcher = etcdBooking.getWatcher();
    if (watcher != null) {
        watcher.close();
    }
    return CompletableFuture.completedFuture(null);
}
 
Example #4
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ConfigBooking booking) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    EtcdConfigBooking etcdBooking = (EtcdConfigBooking) booking;
    //先查询
    ByteSequence key = ByteSequence.from(etcdBooking.getPath(), UTF_8);
    //先查询,无异常后添加watcher,若结果不为空,通知FULL事件
    client.getKVClient().get(key).whenComplete((res, err) -> {
        if (!isOpen()) {
            future.completeExceptionally(new IllegalStateException("controller is closed."));
        } else if (err != null) {
            logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getInterface(), err.getMessage()), err);
            future.completeExceptionally(err);
        } else {
            List<WatchEvent> events = new ArrayList<>();
            res.getKvs().forEach(kv -> events.add(new WatchEvent(kv, null, PUT)));
            etcdBooking.onUpdate(events, res.getHeader().getRevision());
            //添加watch
            try {
                WatchOption watchOption = WatchOption.newBuilder().withPrefix(key).build();
                Watch.Watcher watcher = client.getWatchClient().watch(key, watchOption, etcdBooking);
                etcdBooking.setWatcher(watcher);
                future.complete(null);
            } catch (Exception e) {
                logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getInterface(), e.getMessage()), e);
                future.completeExceptionally(e);
            }
        }
    });
    return future;
}
 
Example #5
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doUnsubscribe(final ConfigBooking booking) {
    EtcdConfigBooking etcdBooking = (EtcdConfigBooking) booking;
    Watch.Watcher watcher = etcdBooking.getWatcher();
    if (watcher != null) {
        watcher.close();
    }
    return CompletableFuture.completedFuture(null);
}
 
Example #6
Source File: EtcdCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
    Watch.Listener listener = Watch.listener(response -> {
        for (WatchEvent each : response.getEvents()) {
            DataChangedEvent.ChangedType changedType = getEventChangedType(each);
            if (DataChangedEvent.ChangedType.IGNORED != changedType) {
                dataChangedEventListener.onChange(new DataChangedEvent(each.getKeyValue().getKey().toString(Charsets.UTF_8), each.getKeyValue().getValue().toString(Charsets.UTF_8), changedType));
            }
        }
    });
    client.getWatchClient().watch(ByteSequence.from(key, Charsets.UTF_8), listener);
}
 
Example #7
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatchUpdate() {
    doAnswer(invocationOnMock -> {
        Watch.Listener listener = (Watch.Listener) invocationOnMock.getArguments()[1];
        listener.onNext(buildWatchResponse(WatchEvent.EventType.PUT));
        return mock(Watch.Watcher.class);
    }).when(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
    centerRepository.watch("key1", dataChangedEvent -> {
    });
    verify(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
}
 
Example #8
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatchDelete() {
    doAnswer(invocationOnMock -> {
        Watch.Listener listener = (Watch.Listener) invocationOnMock.getArguments()[1];
        listener.onNext(buildWatchResponse(WatchEvent.EventType.DELETE));
        return mock(Watch.Watcher.class);
    }).when(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
    centerRepository.watch("key1", dataChangedEvent -> {
    });
    verify(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
}
 
Example #9
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatchIgnored() {
    doAnswer(invocationOnMock -> {
        Watch.Listener listener = (Watch.Listener) invocationOnMock.getArguments()[1];
        listener.onNext(buildWatchResponse(WatchEvent.EventType.UNRECOGNIZED));
        return mock(Watch.Watcher.class);
    }).when(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
    centerRepository.watch("key1", dataChangedEvent -> {
    });
    verify(watch).watch(any(ByteSequence.class), any(Watch.Listener.class));
}
 
Example #10
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public Watch.Watcher getWatcher() {
    return watcher;
}
 
Example #11
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public void setWatcher(Watch.Watcher watcher) {
    this.watcher = watcher;
}
 
Example #12
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public Watch.Watcher getWatcher() {
    return watcher;
}
 
Example #13
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public void setWatcher(Watch.Watcher watcher) {
    this.watcher = watcher;
}
 
Example #14
Source File: OpLogClientFactory.java    From kkbinlog with Apache License 2.0 4 votes vote down vote up
/**
 * 注册Client列表更新监听
 *
 * @param binaryLogConfig
 * @param opLogEventHandlerFactory
 */
private void registerMetaDataWatcher(BinaryLogConfig binaryLogConfig, OpLogEventHandlerFactory opLogEventHandlerFactory) {

    String namespace = binaryLogConfig.getNamespace();
    String binLogClientSet = binaryLogConfig.getBinLogClientSet();

    Watch watchClient = etcdClient.getWatchClient();
    watchClient.watch(
            ByteSequence.from(etcdKeyPrefixUtil.withPrefix(namespace).concat(Constants.PATH_SEPARATOR).concat(binLogClientSet), StandardCharsets.UTF_8),
            WatchOption.newBuilder().withNoDelete(true).build(),
            new Watch.Listener() {
                @Override
                public void onNext(WatchResponse response) {
                    List<WatchEvent> eventList = response.getEvents();
                    for (WatchEvent event : eventList) {
                        if (WatchEvent.EventType.PUT.equals(event.getEventType())) {

                            KeyValue currentKV = event.getKeyValue();
                            Set<ClientInfo> currentClientInfoSet = getClientInfos(currentKV);

                            currentClientInfoSet
                                    .stream()
                                    .collect(Collectors.groupingBy(ClientInfo::getDatabaseEvent))
                                    .forEach(opLogEventHandlerFactory::updateClientBatch);
                        }
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    log.error("Watch clientInfo list change error.", throwable);
                }

                @Override
                public void onCompleted() {
                    log.info("Watch clientInfo list change completed.");
                }
            }
    );

}