How to Use Jedis in Java for Redis Access
To use
Jedis in Java, first add the Jedis library to your project, then create a Jedis instance to connect to Redis. Use this instance to run Redis commands like set and get, and always close the connection after use.Syntax
The basic syntax to use Jedis involves creating a Jedis object with the Redis server address and port, then calling Redis commands on this object. Finally, close the connection to free resources.
- new Jedis(host, port): Connects to Redis server.
- jedis.set(key, value): Stores a value by key.
- jedis.get(key): Retrieves the value by key.
- jedis.close(): Closes the connection.
java
Jedis jedis = new Jedis("localhost", 6379); jedis.set("key", "value"); String value = jedis.get("key"); jedis.close();
Example
This example shows how to connect to Redis, set a key-value pair, retrieve it, and print the result. It demonstrates the basic usage of Jedis in Java.
java
import redis.clients.jedis.Jedis; public class JedisExample { public static void main(String[] args) { // Connect to Redis server on localhost try (Jedis jedis = new Jedis("localhost", 6379)) { // Set a key-value pair jedis.set("language", "Java"); // Get the value for the key String value = jedis.get("language"); // Print the value System.out.println("Stored value: " + value); } catch (Exception e) { System.out.println("Error connecting to Redis: " + e.getMessage()); } } }
Output
Stored value: Java
Common Pitfalls
Common mistakes when using Jedis include:
- Not closing the
Jedisconnection, which can cause resource leaks. - Assuming Redis is running on default host and port without checking.
- Not handling exceptions when Redis is unreachable.
Always use try-with-resources or finally block to close connections.
java
/* Wrong way: Not closing connection */ Jedis jedis = new Jedis("localhost", 6379); jedis.set("key", "value"); // Missing jedis.close(); /* Right way: Using try-with-resources */ try (Jedis jedis = new Jedis("localhost", 6379)) { jedis.set("key", "value"); }
Quick Reference
| Operation | Jedis Method | Description |
|---|---|---|
| Connect to Redis | new Jedis(host, port) | Create connection to Redis server |
| Set value | jedis.set(key, value) | Store a string value by key |
| Get value | jedis.get(key) | Retrieve the string value by key |
| Close connection | jedis.close() | Release resources and close connection |
Key Takeaways
Always create a Jedis instance with correct host and port to connect to Redis.
Use Jedis methods like set and get to interact with Redis data.
Close the Jedis connection after use to avoid resource leaks.
Handle exceptions to manage Redis connection issues gracefully.