io.etcd.jetcd.options.PutOption Java Examples

The following examples show how to use io.etcd.jetcd.options.PutOption. 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: KVTest.java    From jetcd with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedTxn() throws Exception {
    ByteSequence foo = bytesOf("txn_foo");
    ByteSequence bar = bytesOf("txn_bar");
    ByteSequence barz = bytesOf("txn_barz");
    ByteSequence abc = bytesOf("txn_abc");
    ByteSequence oneTwoThree = bytesOf("txn_123");

    Txn txn = kvClient.txn();
    Cmp cmp = new Cmp(foo, Cmp.Op.EQUAL, CmpTarget.version(0));
    CompletableFuture<io.etcd.jetcd.kv.TxnResponse> txnResp = txn.If(cmp)
        .Then(Op.put(foo, bar, PutOption.DEFAULT),
            Op.txn(null, new Op[] { Op.put(abc, oneTwoThree, PutOption.DEFAULT) }, null))
        .Else(Op.put(foo, barz, PutOption.DEFAULT)).commit();
    txnResp.get();

    GetResponse getResp = kvClient.get(foo).get();
    assertThat(getResp.getKvs()).hasSize(1);
    assertThat(getResp.getKvs().get(0).getValue().toString(UTF_8)).isEqualTo(bar.toString(UTF_8));

    GetResponse getResp2 = kvClient.get(abc).get();
    assertThat(getResp2.getKvs()).hasSize(1);
    assertThat(getResp2.getKvs().get(0).getValue().toString(UTF_8)).isEqualTo(oneTwoThree.toString(UTF_8));
}
 
Example #2
Source File: KVTest.java    From jetcd with Apache License 2.0 6 votes vote down vote up
@Test
public void testTxnForCmpOpNotEqual() throws Exception {
    ByteSequence sampleKey = bytesOf("txn_key");
    ByteSequence sampleValue = bytesOf("xyz");
    ByteSequence cmpValue = bytesOf("abc");
    ByteSequence putValue = bytesOf("XYZ");
    ByteSequence putValueNew = bytesOf("ABC");
    // put the original txn key value pair
    kvClient.put(sampleKey, sampleValue).get();

    // construct txn operation
    Txn txn = kvClient.txn();
    Cmp cmp = new Cmp(sampleKey, Cmp.Op.NOT_EQUAL, CmpTarget.value(cmpValue));
    CompletableFuture<io.etcd.jetcd.kv.TxnResponse> txnResp = txn.If(cmp)
        .Then(Op.put(sampleKey, putValue, PutOption.DEFAULT)).Else(Op.put(sampleKey, putValueNew, PutOption.DEFAULT))
        .commit();
    txnResp.get();
    // get the value
    GetResponse getResp = kvClient.get(sampleKey).get();
    assertThat(getResp.getKvs()).hasSize(1);
    assertThat(getResp.getKvs().get(0).getValue().toString(UTF_8)).isEqualTo(putValue.toString(UTF_8));
}
 
Example #3
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 #4
Source File: KVTest.java    From jetcd with Apache License 2.0 6 votes vote down vote up
@Test
public void testTxn() throws Exception {
    ByteSequence sampleKey = bytesOf("txn_key");
    ByteSequence sampleValue = bytesOf("xyz");
    ByteSequence cmpValue = bytesOf("abc");
    ByteSequence putValue = bytesOf("XYZ");
    ByteSequence putValueNew = bytesOf("ABC");
    // put the original txn key value pair
    kvClient.put(sampleKey, sampleValue).get();

    // construct txn operation
    Txn txn = kvClient.txn();
    Cmp cmp = new Cmp(sampleKey, Cmp.Op.GREATER, CmpTarget.value(cmpValue));
    CompletableFuture<io.etcd.jetcd.kv.TxnResponse> txnResp = txn.If(cmp)
        .Then(Op.put(sampleKey, putValue, PutOption.DEFAULT)).Else(Op.put(sampleKey, putValueNew, PutOption.DEFAULT))
        .commit();
    txnResp.get();
    // get the value
    GetResponse getResp = kvClient.get(sampleKey).get();
    assertThat(getResp.getKvs()).hasSize(1);
    assertThat(getResp.getKvs().get(0).getValue().toString(UTF_8)).isEqualTo(putValue.toString(UTF_8));
}
 
Example #5
Source File: KVImpl.java    From jetcd with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<PutResponse> put(ByteSequence key, ByteSequence value, PutOption option) {
    checkNotNull(key, "key should not be null");
    checkNotNull(value, "value should not be null");
    checkNotNull(option, "option should not be null");

    PutRequest request = PutRequest.newBuilder()
        .setKey(Util.prefixNamespace(key.getByteString(), namespace))
        .setValue(value.getByteString())
        .setLease(option.getLeaseId())
        .setPrevKv(option.getPrevKV())
        .build();

    return connectionManager.execute(
        () -> stub.put(request),
        response -> new PutResponse(response, namespace),
        Util::isRetryable);
}
 
Example #6
Source File: EtcdServiceImpl.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
@Override
public void updateServiceStatus(String serviceKey, ServiceStatus status, long leaseId) throws Exception {

    KV client = etcdClient.getKVClient();
    client.put(ByteSequence.from(etcdKeyPrefixUtil.withPrefix(Constants.SERVICE_STATUS_PATH).concat(serviceKey), StandardCharsets.UTF_8),
            ByteSequence.from(JSON.toJSONString(status), StandardCharsets.UTF_8),
            PutOption.newBuilder().withLeaseId(leaseId).build())
            .get();
}
 
Example #7
Source File: KVTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutWithNotExistLease() throws ExecutionException, InterruptedException {
    PutOption option = PutOption.newBuilder().withLeaseId(99999).build();
    CompletableFuture<PutResponse> future = kvClient.put(SAMPLE_KEY, SAMPLE_VALUE, option);
    assertThatExceptionOfType(ExecutionException.class)
        .isThrownBy(future::get).withMessageEndingWith("etcdserver: requested lease not found");
}
 
Example #8
Source File: LeaseTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeToLiveWithKeys() throws ExecutionException, InterruptedException {
    long ttl = 5;
    long leaseID = leaseClient.grant(ttl).get().getID();
    PutOption putOption = PutOption.newBuilder().withLeaseId(leaseID).build();
    kvClient.put(KEY_2, VALUE, putOption).get();

    LeaseOption leaseOption = LeaseOption.newBuilder().withAttachedKeys().build();
    LeaseTimeToLiveResponse resp = leaseClient.timeToLive(leaseID, leaseOption).get();
    assertThat(resp.getTTl()).isGreaterThan(0);
    assertThat(resp.getGrantedTTL()).isEqualTo(ttl);
    assertThat(resp.getKeys().size()).isEqualTo(1);
    assertThat(resp.getKeys().get(0)).isEqualTo(KEY_2);
}
 
Example #9
Source File: LeaseTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeepAliveOnce() throws ExecutionException, InterruptedException {
    long leaseID = leaseClient.grant(2).get().getID();
    kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get();
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1);
    LeaseKeepAliveResponse rp = leaseClient.keepAliveOnce(leaseID).get();
    assertThat(rp.getTTL()).isGreaterThan(0);
}
 
Example #10
Source File: LeaseTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevoke() throws Exception {
    long leaseID = leaseClient.grant(5).get().getID();
    kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get();
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1);
    leaseClient.revoke(leaseID).get();
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0);
}
 
Example #11
Source File: LeaseTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGrantWithTimeout() throws Exception {
    long leaseID = leaseClient.grant(5, 10, TimeUnit.SECONDS).get().getID();
    kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get();
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1);

    Thread.sleep(6000L);
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0);

    tearDown();
    assertThatExceptionOfType(ExecutionException.class)
        .isThrownBy(() -> leaseClient.grant(5, 2, TimeUnit.SECONDS).get().getID());
    setUp();
}
 
Example #12
Source File: LeaseTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGrant() throws Exception {
    long leaseID = leaseClient.grant(5).get().getID();

    kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get();
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1);

    Thread.sleep(6000);
    assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0);
}
 
Example #13
Source File: KVNamespaceTest.java    From jetcd with Apache License 2.0 5 votes vote down vote up
/**
 * Put key-value pair and return whether has previous KV.
 */
private static boolean putKVWithAssertion(KV kvClient, ByteSequence key, ByteSequence value, ByteSequence prevValue)
    throws Exception {
    CompletableFuture<PutResponse> feature = kvClient.put(key, value, PutOption.newBuilder().withPrevKV().build());
    PutResponse response = feature.get();
    if (prevValue != null) {
        assertThat(response.hasPrevKv()).isTrue();
        assertThat(response.getPrevKv().getKey()).isEqualTo(key);
        assertThat(response.getPrevKv().getValue()).isEqualTo(prevValue);
    }
    return response.hasPrevKv();
}
 
Example #14
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void assertPersistEphemeral() {
    centerRepository.persistEphemeral("key1", "value1");
    verify(lease).grant(anyLong());
    verify(lease).keepAlive(anyLong(), any(StreamObserver.class));
    verify(kv).put(any(ByteSequence.class), any(ByteSequence.class), any(PutOption.class));
}
 
Example #15
Source File: EtcdCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public void persistEphemeral(final String key, final String value) {
    long leaseId = client.getLeaseClient().grant(this.etcdProperties.getValue(EtcdPropertyKey.TIME_TO_LIVE_SECONDS)).get().getID();
    client.getLeaseClient().keepAlive(leaseId, Observers.observer(response -> { }));
    client.getKVClient().put(ByteSequence.from(key, Charsets.UTF_8), ByteSequence.from(value, Charsets.UTF_8), PutOption.newBuilder().withLeaseId(leaseId).build()).get();
}
 
Example #16
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doRegister(final Registion registion) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (leaseId <= 0) {
        //没有租约
        future.completeExceptionally(new IllegalStateException(
                String.format("Error occurs while register provider of %s, caused by no leaseId. retry....", registion.getService())));
    } else {
        //有租约
        PutOption putOption = PutOption.newBuilder().withLeaseId(leaseId).build();
        ByteSequence key = ByteSequence.from(registion.getPath(), UTF_8);
        ByteSequence value = ByteSequence.from(registion.getUrl().toString(), UTF_8);
        client.getKVClient().put(key, value, putOption).whenComplete((r, t) -> {
            if (!isOpen()) {
                //已经关闭,或者创建了新的客户端
                future.completeExceptionally(new IllegalStateException("controller is closed."));
            } else if (t != null) {
                //TODO 判断租期失效异常,触发重连逻辑
                logger.error(String.format("Error occurs while register provider of %s, caused by %s. retry....",
                        registion.getPath(), t.getMessage()), t);
                future.completeExceptionally(t);
            } else {
                future.complete(null);
            }
        });
    }
    return future;
}
 
Example #17
Source File: KVNamespaceTest.java    From jetcd with Apache License 2.0 4 votes vote down vote up
@Test
public void testNestedTxn() throws Exception {
    // kvClient without namespace used as the judge for the final result
    kvClient = Client.builder().endpoints(cluster.getClientEndpoints()).build().getKVClient();
    // kvClient with one namespace used to test operations with namespace
    ByteSequence namespace = ByteSequence
        .from(TestUtil.randomByteSequence().getByteString().concat(ByteSequence.NAMESPACE_DELIMITER.getByteString()));
    kvClientWithNamespace = Client.builder().endpoints(cluster.getClientEndpoints()).namespace(namespace).build()
        .getKVClient();

    ByteSequence cmpKey1 = getNonexistentKey();
    putKVWithAssertion(kvClient, cmpKey1, TestUtil.randomByteSequence(), null);

    ByteSequence cmpKey2 = getNonexistentKey();
    putKVWithAssertion(kvClientWithNamespace, cmpKey2, TestUtil.randomByteSequence(), null);

    ByteSequence key1 = getNonexistentKey();
    ByteSequence value1 = TestUtil.randomByteSequence();
    putKVWithAssertion(kvClientWithNamespace, key1, value1, null);

    ByteSequence key2 = getNonexistentKey();
    ByteSequence value2 = TestUtil.randomByteSequence();
    putKVWithAssertion(kvClientWithNamespace, key2, value2, null);

    {
        Txn txn = kvClientWithNamespace.txn();
        ByteSequence nextValue1 = TestUtil.randomByteSequence();
        CompletableFuture<TxnResponse> txnFuture = txn.If(new Cmp(cmpKey1, Cmp.Op.EQUAL, CmpTarget.version(0)))
            .Then(Op.txn(new Cmp[] { new Cmp(cmpKey2, Cmp.Op.GREATER, CmpTarget.version(0)) },
                new Op[] { Op.put(key1, nextValue1, PutOption.newBuilder().withPrevKV().build()) },
                new Op[] {
                        Op.put(key2, TestUtil.randomByteSequence(), PutOption.newBuilder().withPrevKV().build()) }))
            .Else(Op.txn(new Cmp[] { new Cmp(cmpKey2, Cmp.Op.GREATER, CmpTarget.version(0)) },
                new Op[] {
                        Op.put(key2, TestUtil.randomByteSequence(), PutOption.newBuilder().withPrevKV().build()) },
                new Op[] {
                        Op.put(key1, TestUtil.randomByteSequence(), PutOption.newBuilder().withPrevKV().build()) }))
            .commit();
        TxnResponse response = txnFuture.get();
        assertThat(response.getTxnResponses().size()).isEqualTo(1);
        assertThat(response.getTxnResponses().get(0).getPutResponses().size()).isEqualTo(1);
        assertThat(response.getTxnResponses().get(0).getPutResponses().get(0).hasPrevKv()).isTrue();
        assertThat(response.getTxnResponses().get(0).getPutResponses().get(0).getPrevKv().getKey()).isEqualTo(key1);
        assertThat(response.getTxnResponses().get(0).getPutResponses().get(0).getPrevKv().getValue()).isEqualTo(value1);
        value1 = nextValue1;
        assertExistentKey(kvClient, ByteSequence.from(namespace.getByteString().concat(key1.getByteString())), value1);
    }
}
 
Example #18
Source File: KVImpl.java    From jetcd with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<PutResponse> put(ByteSequence key, ByteSequence value) {
    return this.put(key, value, PutOption.DEFAULT);
}
 
Example #19
Source File: Op.java    From jetcd with Apache License 2.0 4 votes vote down vote up
protected PutOp(ByteString key, ByteString value, PutOption option) {
    super(Type.PUT, key);
    this.value = value;
    this.option = option;
}
 
Example #20
Source File: Op.java    From jetcd with Apache License 2.0 4 votes vote down vote up
public static PutOp put(ByteSequence key, ByteSequence value, PutOption option) {
    return new PutOp(ByteString.copyFrom(key.getBytes()), ByteString.copyFrom(value.getBytes()), option);
}
 
Example #21
Source File: KV.java    From jetcd with Apache License 2.0 2 votes vote down vote up
/**
 * put a key-value pair into etcd with option.
 *
 * @param  key    key in ByteSequence
 * @param  value  value in ByteSequence
 * @param  option PutOption
 * @return        PutResponse
 */
CompletableFuture<PutResponse> put(ByteSequence key, ByteSequence value, PutOption option);