io.etcd.jetcd.Client Java Examples

The following examples show how to use io.etcd.jetcd.Client. 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: EtcdDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Create an etcd data-source. The connection configuration will be retrieved from {@link EtcdConfig}.
 *
 * @param key    config key
 * @param parser data parser
 */
public EtcdDataSource(String key, Converter<String, T> parser) {
    super(parser);
    if (!EtcdConfig.isAuthEnable()) {
        this.client = Client.builder()
            .endpoints(EtcdConfig.getEndPoints().split(",")).build();
    } else {
        this.client = Client.builder()
            .endpoints(EtcdConfig.getEndPoints().split(","))
            .user(ByteSequence.from(EtcdConfig.getUser(), charset))
            .password(ByteSequence.from(EtcdConfig.getPassword(), charset))
            .authority(EtcdConfig.getAuthority())
            .build();
    }
    this.key = key;
    loadInitialConfig();
    initWatcher();
}
 
Example #3
Source File: EtcdClusterUsingTest.java    From jetcd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseEtcd() throws Exception {
    try (EtcdCluster etcd = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false)) {
        etcd.start();
        try (Client client = Client.builder().endpoints(etcd.getClientEndpoints()).build()) {
            try (KV kvClient = client.getKVClient()) {
                ByteSequence key = bytesOf("test_key");
                ByteSequence value = bytesOf("test_value");
                kvClient.put(key, value).get();

                CompletableFuture<GetResponse> getFuture = kvClient.get(key);
                GetResponse response = getFuture.get();
                List<KeyValue> values = response.getKvs();
                assertThat(values.size()).isEqualTo(1);
                KeyValue value1 = values.get(0);
                assertThat(value1.getValue()).isEqualTo(value);
                assertThat(value1.getKey()).isEqualTo(key);
            }
        }
    }
}
 
Example #4
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@SuppressWarnings("unchecked")
private Client mockClient() {
    when(client.getKVClient()).thenReturn(kv);
    when(kv.get(any(ByteSequence.class))).thenReturn(getFuture);
    when(kv.get(any(ByteSequence.class), any(GetOption.class))).thenReturn(getFuture);
    when(kv.put(any(ByteSequence.class), any(ByteSequence.class))).thenReturn(putFuture);
    when(kv.put(any(ByteSequence.class), any(ByteSequence.class), any(PutOption.class))).thenReturn(putFuture);
    when(getFuture.get()).thenReturn(getResponse);
    when(client.getLeaseClient()).thenReturn(lease);
    when(lease.grant(anyLong())).thenReturn(leaseFuture);
    when(leaseFuture.get()).thenReturn(leaseGrantResponse);
    when(leaseGrantResponse.getID()).thenReturn(123L);
    when(client.getWatchClient()).thenReturn(watch);
    return client;
}
 
Example #5
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
protected CompletableFuture<Void> doConnect() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    client = Client.builder().lazyInitialization(false).endpoints(registry.address).authority(registry.authority).build();
    //生成统一续约id,并启动续约task
    CompletableFuture<LeaseGrantResponse> grant = client.getLeaseClient().grant(registry.timeToLive / 1000);
    grant.whenComplete((res, err) -> {
        if (err != null) {
            client.close();
            client = null;
            future.completeExceptionally(err);
        } else {
            leaseId = res.getID();
            leaseErr.set(0);
            //续约
            timer().add(new Timer.DelegateTask(leaseTaskName, SystemClock.now() + leaseInterval, this::lease));
            future.complete(null);
        }
    });
    return future;
}
 
Example #6
Source File: EtcdWatchManager.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
public EtcdWatchManager(String etcdStr, String etcdPath) {

        if (Preconditions.isNotBlank(etcdStr)) {
            client = Client.builder().endpoints(etcdStr).build();
        }

        if (Preconditions.isBlank(etcdPath)) {
            this.path = Constant.DEFAULT_REGISTRY_PATH;
        } else {
            this.path = etcdPath;
        }

        vertx = Vertx.vertx();
    }
 
Example #7
Source File: MavenPluginTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testEtcdServerStarted() throws Exception {
    final String filePath = "target/jetcd-launcher-maven-plugin/endpoint";
    final String endpoint = Files.asCharSource(new File(filePath), US_ASCII).readFirstLine();

    try (Client client = Client.builder().endpoints(endpoint).build()) {
        assertThat(client.getKVClient().get(Constants.NULL_KEY).get(7, TimeUnit.SECONDS).getCount()).isEqualTo(0);
    }
}
 
Example #8
Source File: CommandWatch.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Client client) throws Exception {
    CountDownLatch latch = new CountDownLatch(maxEvents);
    Watcher watcher = null;

    try {
        ByteSequence watchKey = ByteSequence.from(key, Charsets.UTF_8);
        WatchOption watchOpts = WatchOption.newBuilder().withRevision(rev).build();

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

            latch.countDown();
        });

        latch.await();
    } catch (Exception e) {
        if (watcher != null) {
            watcher.close();
        }

        throw e;
    }
}
 
Example #9
Source File: CommandGet.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Client client) throws Exception {
    GetResponse getResponse = client.getKVClient()
        .get(ByteSequence.from(key, UTF_8), GetOption.newBuilder().withRevision(rev).build()).get();

    if (getResponse.getKvs().isEmpty()) {
        // key does not exist
        return;
    }

    LOGGER.info(key);
    LOGGER.info(getResponse.getKvs().get(0).getValue().toString(UTF_8));
}
 
Example #10
Source File: Main.java    From jetcd with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Args global = new Args();
    CommandGet getCmd = new CommandGet();
    CommandPut putCmd = new CommandPut();
    CommandWatch watchCmd = new CommandWatch();

    JCommander jc = JCommander.newBuilder().addObject(global).addCommand("get", getCmd).addCommand("put", putCmd)
        .addCommand("watch", watchCmd).build();

    jc.parse(args);

    String cmd = jc.getParsedCommand();
    if (cmd == null || global.help) {
        jc.usage();
        return;
    }

    try (Client client = Client.builder().endpoints(global.endpoints.split(",")).build()) {
        switch (cmd) {
            case "get":
                getCmd.accept(client);
                break;
            case "put":
                putCmd.accept(client);
                break;
            case "watch":
                watchCmd.accept(client);
                break;
        }
    } catch (Exception e) {
        LOGGER.error(cmd + " Error {}", e);
        System.exit(1);
    }
}
 
Example #11
Source File: CommandPut.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Client client) throws Exception {
    client.getKVClient()
        .put(ByteSequence.from(keyValue.get(0), Charsets.UTF_8), ByteSequence.from(keyValue.get(1), Charsets.UTF_8)).get();

    LOGGER.info("OK");
}
 
Example #12
Source File: EtcdDataSourceTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadSource() throws Exception {
    EtcdDataSource dataSource = new EtcdDataSource("foo", value -> value);
    KV kvClient = Client.builder()
            .endpoints(endPoints)
            .build().getKVClient();

    kvClient.put(ByteSequence.from("foo".getBytes()), ByteSequence.from("test".getBytes()));
    Assert.assertNotNull(dataSource.readSource().equals("test"));

    kvClient.put(ByteSequence.from("foo".getBytes()), ByteSequence.from("test2".getBytes()));
    Assert.assertNotNull(dataSource.getProperty().equals("test2"));
}
 
Example #13
Source File: EtcdConfigSender.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {


        String rule_key = "sentinel_demo_rule_key";

        Client client = Client.builder()
                .endpoints("http://127.0.0.1:2379")
                .user(ByteSequence.from("root".getBytes()))
                .password(ByteSequence.from("12345".getBytes()))
                .build();
        final String rule = "[\n"
                + "  {\n"
                + "    \"resource\": \"TestResource\",\n"
                + "    \"controlBehavior\": 0,\n"
                + "    \"count\": 5.0,\n"
                + "    \"grade\": 1,\n"
                + "    \"limitApp\": \"default\",\n"
                + "    \"strategy\": 0\n"
                + "  }\n"
                + "]";
        client.getKVClient()
                .put(ByteSequence.from(rule_key.getBytes()), ByteSequence.from(rule.getBytes()));

        System.out.println("setting rule success");
        Thread.sleep(10000);

    }
 
Example #14
Source File: EtcdConfig.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
@Bean
public Client etcdClient() {

    Client client  = Client
            .builder()
            .endpoints(Util.toURIs(endpoints))
            //.authority(authority)
            //.user(ByteSequence.from(username, StandardCharsets.UTF_8))
            //.password(ByteSequence.from(password, StandardCharsets.UTF_8))
            .build();

    return client;
}
 
Example #15
Source File: MongoDBDistributorServiceImpl.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
public MongoDBDistributorServiceImpl(OpLogClientFactory opLogClientFactory, BinaryLogConfigContainer binaryLogConfigContainer, EtcdService etcdService, Client etcdClient, EtcdKeyPrefixUtil etcdKeyPrefixUtil,@Qualifier("opLogDataPublisher") DataPublisher dataPublisher) {
    this.opLogClientFactory = opLogClientFactory;
    this.binaryLogConfigContainer = binaryLogConfigContainer;
    this.etcdService = etcdService;
    this.etcdClient = etcdClient;
    this.etcdKeyPrefixUtil = etcdKeyPrefixUtil;
    this.dataPublisher = dataPublisher;
}
 
Example #16
Source File: OpLogClientFactory.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
public OpLogClientFactory(RedissonClient redissonClient, @Qualifier("opLogDataPublisher") DataPublisher dataPublisher, EtcdService etcdService, Client etcdClient, BinaryLogConfigContainer binaryLogConfigContainer, EtcdKeyPrefixUtil etcdKeyPrefixUtil) {
    this.redissonClient = redissonClient;
    this.dataPublisher = dataPublisher;
    this.etcdService = etcdService;
    this.etcdClient = etcdClient;
    this.binaryLogConfigContainer = binaryLogConfigContainer;
    this.etcdKeyPrefixUtil = etcdKeyPrefixUtil;
}
 
Example #17
Source File: EtcdCenterRepository.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
@Override
public void init(final CenterConfiguration config) { 
    this.etcdProperties = new EtcdProperties(props);
    client = Client.builder().endpoints(Util.toURIs(Splitter.on(",").trimResults().splitToList(config.getServerLists()))).build();
}
 
Example #18
Source File: EtcdDataSourceTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testDynamicUpdate() throws InterruptedException {
    String demo_key = "etcd_demo_key";
    ReadableDataSource<String, List<FlowRule>> flowRuleEtcdDataSource = new EtcdDataSource<>(demo_key, (value) -> JSON.parseArray(value, FlowRule.class));
    FlowRuleManager.register2Property(flowRuleEtcdDataSource.getProperty());

    KV kvClient = Client.builder()
            .endpoints(endPoints)
            .build().getKVClient();

    final String rule1 = "[\n"
            + "  {\n"
            + "    \"resource\": \"TestResource\",\n"
            + "    \"controlBehavior\": 0,\n"
            + "    \"count\": 5.0,\n"
            + "    \"grade\": 1,\n"
            + "    \"limitApp\": \"default\",\n"
            + "    \"strategy\": 0\n"
            + "  }\n"
            + "]";

    kvClient.put(ByteSequence.from(demo_key.getBytes()), ByteSequence.from(rule1.getBytes()));
    Thread.sleep(1000);

    FlowRule flowRule = FlowRuleManager.getRules().get(0);
    Assert.assertTrue(flowRule.getResource().equals("TestResource"));
    Assert.assertTrue(flowRule.getCount() == 5.0);
    Assert.assertTrue(flowRule.getGrade() == 1);

    final String rule2 = "[\n"
            + "  {\n"
            + "    \"resource\": \"TestResource\",\n"
            + "    \"controlBehavior\": 0,\n"
            + "    \"count\": 6.0,\n"
            + "    \"grade\": 3,\n"
            + "    \"limitApp\": \"default\",\n"
            + "    \"strategy\": 0\n"
            + "  }\n"
            + "]";

    kvClient.put(ByteSequence.from(demo_key.getBytes()), ByteSequence.from(rule2.getBytes()));
    Thread.sleep(1000);

    flowRule = FlowRuleManager.getRules().get(0);
    Assert.assertTrue(flowRule.getResource().equals("TestResource"));
    Assert.assertTrue(flowRule.getCount() == 6.0);
    Assert.assertTrue(flowRule.getGrade() == 3);


}
 
Example #19
Source File: LeaderSelectorTest.java    From kkbinlog with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    client = Client.builder().endpoints("http://localhost:2379").build();
    lock = client.getLockClient();
    lease = client.getLeaseClient();
}
 
Example #20
Source File: MysqlDistributorServiceImpl.java    From kkbinlog with Apache License 2.0 4 votes vote down vote up
public MysqlDistributorServiceImpl(BinLogClientFactory binLogClientFactory, Client etcdClient, EtcdKeyPrefixUtil etcdKeyPrefixUtil, @Qualifier("binlogDataPublisher")DataPublisher dataPublisher) {
    this.binLogClientFactory = binLogClientFactory;
    this.etcdClient = etcdClient;
    this.etcdKeyPrefixUtil = etcdKeyPrefixUtil;
    this.dataPublisher = dataPublisher;
}