How to make the Java secure connection for Redis

This is a step-by-step instruction and it uses Jedis client driver to show the sample.

  1. This requires the certificate to the Redis database instance.
  2. Get the “certificate” string, see below as an example.
"certificate": { "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUREekNDQWZlZ0F3SUJBZ0lKQU5FSDU4..."
}
  1. Copy, decode, and save the certificate to a file.
 echo "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUREekNDQWZlZ0F3SUJBZ0lKQU5FSDU4..." | base64 -D > cert.crt 

  1. Copy the file cert.crt to the $JAVA_HOME/jre/lib/security .
  2. Import the certificate to the trusted root certificate of the JAVA (usually called “cacerts”) by using keytool import command. For example,
sudo keytool -importcert -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/security/cacerts
 -storepass changeit -file cert.crt -alias "redis_key" 

  1. Write the Java program. There are several Java clients for Redis – https://redislabs.com/lp/redis-java/ I use Jedis(jedis-3.0.0.jar) as an example as below. Please change the uri_string to your database for redis instance uri_string.
import java.net.URI;
    
import redis.clients.jedis.Jedis;
    
public class redis_jedis_sample {

      public static void main(String[] args) throws Exception {
            String redis_uri = "rediss://admin:***@47131ae0-6508-4b8b-939d-6eaaf5f36abc.databases.appdomain.cloud:31503/0";
            Jedis jedis = new Jedis(URI.create(redis_uri));
            jedis.connect();
            System.out.println(jedis.ping());
            }
} 

If the java application runs with “PONG” returned, then the connection is successful.