Java Code Examples for io.etcd.jetcd.Watch#listener()

The following examples show how to use io.etcd.jetcd.Watch#listener() . 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: 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);
}