This page walks you through a simple demonstration of how to use TTL (Time To Live) on RawKV. TTL is a data clearing mechanism that automatically deletes data after a specified period of time. For example:

  • If TTL is not used, the data written to TiKV will always exist in TiKV unless it is manually deleted.
  • If TTL is used, and the TTL time of a key is set to one hour, the data of the key will be automatically deleted by TiKV after one hour.

Prerequisites

Before you start, ensure that you have installed TiUP and jshell, and have downloaded the tikv-client JARS file according to TiKV in 5 Minutes.

Step 1: Config TiKV to enable TTL

TTL is disabled by default. To enable it, create a file tikv.yaml using the following configuration.

  1. [storage]
  2. enable-ttl = true

Step 2: Start TiKV Cluster

For this tutorial, only one TiKV node is needed, so the tiup playground command is used.

Show TiUP version:

  1. tiup -v

version >= 1.5.2:

  1. tiup playground --mode tikv-slim --kv.config tikv.yaml

version < 1.5.2:

  1. tiup playground --kv.config tikv.yaml

Step 3: Write the code to test TTL

The following example shows how to verify the TTL works.

Save the following script to file test_raw_ttl.java.

  1. import java.util.*;
  2. import org.tikv.common.TiConfiguration;
  3. import org.tikv.common.TiSession;
  4. import org.tikv.raw.RawKVClient;
  5. import org.tikv.shade.com.google.protobuf.ByteString;
  6. TiConfiguration conf = TiConfiguration.createRawDefault("127.0.0.1:2379");
  7. TiSession session = TiSession.create(conf);
  8. RawKVClient client = session.createRawClient();
  9. // write (k1, v1) with ttl=30 seconds
  10. client.put(ByteString.copyFromUtf8("k1"), ByteString.copyFromUtf8("v1"), 30);
  11. // write (k2, v2) without ttl
  12. client.put(ByteString.copyFromUtf8("k2"), ByteString.copyFromUtf8("v2"));
  13. // get k1 & k2 resturns v1 & v2
  14. System.out.println(client.batchGet(new ArrayList<ByteString>() {{
  15. add(ByteString.copyFromUtf8("k1"));
  16. add(ByteString.copyFromUtf8("k2"));
  17. }}));
  18. // sleep 30 seconds
  19. System.out.println("Sleep 30 seconds.")
  20. Thread.sleep(30000);
  21. // get k1 & k2 returns v2
  22. // k1's ttl is expired
  23. System.out.println(client.batchGet(new ArrayList<ByteString>() {{
  24. add(ByteString.copyFromUtf8("k1"));
  25. add(ByteString.copyFromUtf8("k2"));
  26. }}));

Step 4: Run the code

  1. jshell --class-path tikv-client-java.jar:slf4j-api.jar --startup test_raw_ttl.java
  2. [key: "k1"
  3. value: "v1"
  4. , key: "k2"
  5. value: "v2"
  6. ]
  7. Sleep 30 seconds.
  8. [key: "k2"
  9. value: "v2"
  10. ]

After running the above code, you can find that k1 is automatically deleted when its TTL has expired.