Using Java to operate Redis
To use Java to operate Redis, you first need to import Redis's Java client dependency package. The commonly used Redis Java clients include Jedis and Lettuce. Let's take Jedis as an example to introduce how to use Java to operate Redis.
1. Add Maven dependency:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>
2. Connect Redis in Java code:
import redis.clients.jedis.Jedis;
public class RedisExample {
public static void main(String[] args) {
//Connect Redis
Jedis jedis = new Jedis("localhost", 6379);
//Execute Redis command
jedis.set("key", "value");
//Close Connection
jedis.close();
}
}
3. Data insertion, modification, and query:
import redis.clients.jedis.Jedis;
public class RedisExample {
public static void main(String[] args) {
//Connect Redis
Jedis jedis = new Jedis("localhost", 6379);
//Insert Data
jedis.set("name", "John");
jedis.set("age", "25");
//Modify data
jedis.set("age", "26");
//Query data
String name = jedis.get("name");
String age = jedis.get("age");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
//Close Connection
jedis.close();
}
}
4. Data deletion:
import redis.clients.jedis.Jedis;
public class RedisExample {
public static void main(String[] args) {
//Connect Redis
Jedis jedis = new Jedis("localhost", 6379);
//Delete data
jedis.del("name");
//Close Connection
jedis.close();
}
}
The above code example shows how to use Java to operate Redis, including connecting to Redis, inserting, modifying, querying, and deleting data. In practical use, according to specific needs, more Redis commands can be called to achieve more complex operations.