Is there any way to set the ttl for a state in dapr for Java SDK?
The DaprClient.save()
method does not accept a state object. I could not even find a way to set the TTl through StateOptions
class.
Can anyone help me with this?
According to https://github.com/dapr/java-sdk/issues/627:
It is not possible to set the TTL via the Java SDK. The default approach is to set it via the component configuration though. In any way, being able to utilize TTL depends on the state store you are using. See the TTL column here: https://docs.dapr.io/reference/components-reference/supported-state-stores/
You need to try something like the above:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class DaprStateTTLExample {
private static final String DAPR_SIDECAR_HTTP_PORT = "3500";
private static final String STATE_STORE_NAME = "your-state-store-name";
private static final String KEY = "your-state-key";
private static final String BASE_URL = "http://localhost:" + DAPR_SIDECAR_HTTP_PORT + "/v1.0/state/";
public static void main(String[] args) throws Exception {
// Set the TTL to 60 seconds (adjust as needed)
int ttlInSeconds = 60;
// Create the state object
YourStateObject state = new YourStateObject();
state.setSomeProperty("some value");
// Convert the state object to JSON
String stateJson = YourJsonSerializer.serialize(state);
// Create the HTTP client
HttpClient httpClient = HttpClient.newHttpClient();
// Build the request
String url = BASE_URL + STATE_STORE_NAME;
String payload = String.format("[{\"key\": \"%s\", \"value\": %s, \"options\": {\"ttlInSeconds\": %d}}]", KEY, stateJson, ttlInSeconds);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
// Send the request
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// Check the response
if (response.statusCode() == 200) {
System.out.println("State saved successfully with TTL");
} else {
System.out.println("Failed to save state with TTL. Error: " + response.body());
}
}
// YourStateObject represents the structure of your state
static class YourStateObject {
private String someProperty;
public String getSomeProperty() {
return someProperty;
}
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
}
// YourJsonSerializer represents your JSON serialization logic
static class YourJsonSerializer {
public static String serialize(Object obj) {
// Implement your JSON serialization logic here
return "";
}
}
}