Updated on 2024-08-06 GMT+08:00

Connecting to an Instance Using Java

This section describes how to connect to a GeminiDB Redis instance using Java.

Dependencies on the pom File

<dependency>
     <groupId>redis.clients</groupId>
     <artifactId>jedis</artifactId>
     <version>4.3.2</version>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
     <version>2.3.6.RELEASE</version>
 </dependency>

Example Java Code for Connecting to an Instance Using the Connection Pool

package nosql.cloud.huawei.jedis;
import redis.clients.jedis.*;
public class MainBitMao {
    public static void main(String[] args) {
        //Initialize the Jedis resource pool configuration JedisPoolConfig jedisPoolConfig = new JedisPoolConfig().
        // Set the maximum number of connections in the pool.
        jedisPoolConfig.setMaxTotal(10);
        // Set the maximum number of idle connections allowed by the pool.
        jedisPoolConfig.setMaxIdle(10);
        // Set the minimum number of idle connections retained in the pool.
        jedisPoolConfig.setMinIdle(2);
        // Initialize JedisPool.
        // Note: If the version does not support Access Control List (ACL), the value of user must be null.
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 8635, null, "********");
        // Obtain connections from the pool.
        try (Jedis jedis = jedisPool.getResource()){
            // Initialize the key value.
            String key = "test_key", value = "test_value";
            // do something...
            // Set the string value of a key.
            jedis.set(key, value);
            // Obtain the value of a key by running the GET command.
            jedis.get(key);
            // do something...
        }
        // Disable the pool.
        jedisPool.close();
   }
}