Connect with Java
Establish a connection to your Aiven for Valkey™ service using Java and the jedis
library.
Variables
Replace placeholders in the code sample with values from your service overview page:
Variable | Description |
---|---|
SERVICE_URI | URI for the Aiven for Valkey service connection |
Prerequisites
-
Alternatively, if you choose not to install Maven, manually download the dependencies from the Maven Central Repository and place them in the
lib
folder. -
If you have Maven installed, run the following commands in the
lib
folder to downloadjedis
and its dependencies:mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=redis.clients:jedis:4.1.1:jar -Ddest=lib/jedis-4.1.1.jar \
&& mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.apache.commons:commons-pool2:2.11.1:jar -Ddest=lib/commons-pool2-2.11.1.jar \
&& mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.slf4j:slf4j-api:1.7.35:jar -Ddest=lib/slf4j-api-1.7.35.jar \
&& mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=com.google.code.gson:gson:2.8.9:jar -Ddest=lib/gson-2.8.9.jar
Set up and run
-
Create a file named
ValkeyExample.java
and insert the code below, substituting the placeholder with your Aiven for Valkey URI:import redis.clients.jedis.JedisPooled;
public class ValkeyExample {
public static void main(String[] args) {
if (args.length != 1) {
throw new IllegalArgumentException("Expected only one argument service URI");
} else {
JedisPooled jedisPooled = new JedisPooled(args[0]);
jedisPooled.set("key", "hello world");
System.out.println("The value of key is: " + jedisPooled.get("key"));
}
}
}This code connects to Aiven for Valkey, sets a
key
named key with the valuehello world
(without expiration), then retrieves and prints the value of this key. -
To compile and run the script, replace SERVICE_URI with your actual service URI:
javac -cp "lib/*:." ValkeyExample.java && java -cp "lib/*:." ValkeyExample SERVICE_URI
A successful connection displays:
The value of key is: hello world