Jedis
Jedis is a Java client for interacting with Redis databases. It provides a series of easy-to-use APIs that make it very easy to use Redis in Java applications. Here's how to use Jedis and some notes.
The Jedis Advantage
Lettuce client and Jedis client are compared as follows:
- Lettuce:
- The Lettuce client has no connection alive detection, and the presence of an incorrect connection in the connection pool will result in an error when the request is overrun.
- The Lettuce client does not implement connection pooling detection methods such as testOnBorrow, and is unable to verify connections before using them.
- Jedis:
- Jedis client implements connection pooling checksum configuration such as testOnBorrow, testWhileIdle, testOnReturn.
- Turning on testOnBorrow performs connection checksums before each borrowed connection, which is the most reliable, but affects performance (it probes before each Redis request).
- testWhileIdle can detect connections when they are idle, and a reasonable threshold can be configured to reject abnormal connections in the connection pool in a timely manner to prevent the use of abnormal connections from causing business errors.
- Problems with the connection before the idle connection is detected may cause the service using the connection to report an error, here you can control the detection interval (timeBetweenEvictionRunsMillis) through the parameter.
Therefore, the Jedis client's ability to handle and detect anomalies in the face of connection anomalies, network jitter, and other scenarios is significantly better than Lettuce's, and more reliable.
Jedis uses
1. Introduction of dependencies
If you're using Maven, you can add the Add the following dependency to the
<dependency>
<groupId></groupId>
<artifactId>jedis</artifactId>
<version>5.2.0</version> <!-- Please check the latest version -->
</dependency>
2. Create a Jedis instance
Create a Jedis instance that connects to the Redis server:
import ;
public class JedisExample {
public static void main(String[] args) {
// Create a Jedis instance that connects to localhost:6379.
Jedis jedis = new Jedis("localhost", 6379);
// Perform authentication (if required)
// ("your_password");
// Test the connection
("Connection succeeded: " + ()); // Test the connection.
// Close the connection
(); // Close the connection.
}
}
3. Common operations
- string operation:
// Set the value
("key", "value");
// Get the value
String value = ("key"); ("Fetch value: " + value); // Get value.
("Fetched value: " + value); // Get the value.
- hash operation:
// Set the hash
("user:1000", "name", "Alice"); ("user:1000", "name", "Alice");
("user:1000", "age", "30");
// Get the hash
String name = ("user:1000", "name"); ("user:1000", "name"); // Get the hash.
("User name: " + name); // Get the hash.
- list operation:
// Add an element to the list
("mylist", "item1");
("mylist", "item2").
// Get the list elements
List<String> list = ("mylist", 0, -1); ("mylist", 0, -1); // Get the list elements.
("mylist", 0, -1); ("mylist content: " + list); // Get the list elements.
- set operation:
// Add elements to the set
("myset", "member1");
("myset", "member2").
// Get the members of the set
Set<String> members = ("myset"); ("set members: " + members"); ("set members: " + members")
("Set members: " + members); // Get the set members.
caveat
-
connection management:
- Creating and closing Jedis instances before each operation can lead to performance issues and connection pooling is recommended.
- It is possible to use
JedisPool
to manage connections. - Jedis can manage resources using tr-with-resources
import ; import ; public class JedisPoolExample { public static void main(String[] args) { JedisPoolConfig config = new JedisPoolConfig(); (100); // Maximum number of connections (50); // Maximum number of free connections (10); // Minimum number of free connections (true); // Check connection validity when fetching connections (true); // Check connection validity when idle (60000); // Minimum free connection alive time, 60s (30000); // cleanup thread runtime interval, 30S JedisPool pool = new JedisPool(config, "localhost", 6379); try (Jedis jedisPool, "localhost", 6379); // check for connection validity on idle connections. try (Jedis jedis = ()) { ("Connection succeeded: " + ()); } catch (Exception e) { } catch (Exception e) { (); } catch (Exception e) { } finally { (); } finally { } } }
-
Exception handling:
- When using Jedis, possible exceptions should be handled, such as connection failures, timeouts, and so on.
-
thread safety:
- Jedis instances are not thread-safe and therefore should not share the same instance between multiple threads. Using connection pooling avoids this problem.
-
Redis Configuration:
- Ensure that the Redis service is running properly and adjust the Redis configuration (e.g., maximum number of connections, timeouts, etc.) as needed.
-
Data expiration:
- Redis provides key expiration functionality that can be accessed via the
expire
The command sets the key expiration time to prevent data from occupying memory for a long period of time.
- Redis provides key expiration functionality that can be accessed via the
-
Monitoring and Optimization:
- Monitor Redis performance metrics (e.g., memory usage, command execution time, etc.) and optimize as appropriate.
Connection Pooling Recommended Configuration
parameters | Configuration | Configuration recommendations |
---|---|---|
maxTotal | Maximum connections in | Configured according to the number of Http threads in the Web container to estimate the number of Redis calls that may be made in parallel in a single Http request, for example: Tomcat Connector within the maxConnections configured as 150, each Http request may be executed in parallel 2 Redis requests, on top of which part of the reservation, the It is recommended that the configuration be at least: 150 x 2 + 100= 400 Limitations: Maximum number of connections to a single Redis instance. maxTotal and the product of the number of client nodes (number of CCE containers or business VMs) values should be less than the maximum number of connections to a single Redis instance. For example: Redis master and backup instances are configured with maxClients of 10,000, and a single client maxTotal is configured as 500, then the maximum number of client nodes is 20. |
maxIdle | Maximum free connections, in | The configuration is consistent with maxTotal. |
minIdle | Minimum free connections, in | Generally speaking, it is recommended to configure it as one Xth of maxTotal, for example, the regular configuration here is recommended to be: 100. For performance-sensitive scenarios, in order to prevent the impact of jitter in the number of frequent connections, you can configure it to be consistent with maxIdle, for example: 400. |
maxWaitMillis | Maximum get connection wait time in milliseconds | Get the maximum connection pool waiting time when connecting, based on the longest tolerated failure time for a single operation minus the timeout for executing commands to get the recommended value. For example: the longest tolerated failure time for Http is 15s, and the timeout for Redis requests is set to 10s, then you can configure 5s here. |
timeout | Command execution timeout, in milliseconds | The maximum tolerable timeout for a single execution of Redis commands is selected according to the logic of the business program, and is recommended to be configured to be no less than 210ms for network fault tolerance, etc. Special probing logic or environmental anomaly detection can be appropriately adjusted to reach the second level. |
minEvictableIdleTimeMillis | Idle connection eviction time, greater than the value of the idle connection has not been used will be released, unit: milliseconds | If you want the system not to rebuild broken connections very often, you can configure a larger value here (xx minutes), or configure -1 here and use the idle connection detection for periodic detection. |
timeBetweenEvictionRunsMillis | Idle connection detection interval in milliseconds | Estimated based on the number of idle connections of the system, for example, if the idle connection detection time of the system is configured as 30s, it means that the connection will be detected every 30s, and if an abnormal connection occurs within 30s, connection exclusion will be performed after detection. Configuration is based on the number of connections, if the number of connections is too large, the configuration time is too short, which will result in a waste of request resources. For hundreds of connections, it is recommended to configure 30s, which can be dynamically adjusted according to system needs. |
testOnBorrow | Whether to do connection validity check (ping) when borrowing connections from the resource pool, invalid connections detected will be removed. | For extreme sensitivity of business connections and acceptable performance, it can be configured to True. In general, it is recommended to configure it to False to enable connection idleness detection. |
testWhileIdle | Whether or not to monitor connection validity via ping command during idle resource monitoring, invalid connections will be destroyed. | True |
testOnReturn | Whether to do a connection validity check (ping) when returning a connection to a resource pool; invalid connections will be removed if detected. | False |
maxAttempts | In JedisCluster mode, you can configure the maxAttempts parameter to define the number of retries on failure. | It is recommended to configure between 3 and 5, and the default configuration is 5. According to the combined configuration of the maximum timeout time of the business interface and the timeout of a single request, the maximum configuration is not recommended to exceed 10, otherwise it will result in the processing time of a single request is too long and the interface request is blocked. |
Reference:
- /questions/73242557/jedispool-vs-jedispooled
- /docs/latest/develop/clients/jedis/
- /intl/zh-cn/dcs_faq/
- https:///blog/jedis-pool-optimization