3303. Redis - Using Redis in Java
Redis


Using Redis in Java programs

1. Redis Java Driver

There are many redis clients. We will use Jedis.jar which is for java. Download Jedis.jar from here. Then, include the jedis.jar in java project.

2. Redis Connection

If redis is installed in Ubuntu Virtual Machine, we need to find the ip address of Ubuntu. Settings->Network, click the setting icon. image See the ip address, eg. ‘192.168.182.130’. image

Edit file /etc/redis/redis.conf in Ubuntu. Change bind from ‘127.0.0.1 ::1’ to ‘0.0.0.0 ::1’. Or directly comment out.

bind 127.0.0.1 ::1

Restart redis server.

sudo systemctl restart redis

Check if redis can be access with non-local ip address.

$ redis-cli -h 192.168.182.130
192.168.182.130:6379>ping
PONG

3. Java Program

Three operations.

  • Connect to Redis Server
  • Write data to Redis
  • Read data from Redis
package johnny.java.redis;

import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

public class RedisExample {
    public static void main(String[] args) {
        //Connecting to Redis server on localhost
        Jedis jedis = new Jedis("192.168.182.130");
        System.out.println("Connection to server successfully");
        //check whether server is running or not
        System.out.println("Server is running: "+jedis.ping());

        //set the data in redis string
        jedis.set("tutorial-name", "Redis tutorial");
        System.out.println("Stored string in redis:: "+ jedis.get("username"));

        //store data in redis list
        jedis.lpush("tutorial-list", "Redis");
        jedis.lpush("tutorial-list", "Mongodb");
        jedis.lpush("tutorial-list", "Mysql");
        // Get the stored data and print it
        List<String> list = jedis.lrange("tutorial-list", 0 ,5);

        for(int i = 0; i<list.size(); i++) {
            System.out.println("Stored string in redis:: "+list.get(i));
        }

        //store data in redis list
        // Get the stored data and print it
        Set<String> set = jedis.keys("*");

        for (String key : set) {
            System.out.println("List of stored keys:: "+key);
        }
    }
}

Output.

Connection to server successfully
Server is running: PONG
Stored string in redis:: Redis tutorial
Stored string in redis:: Mysql
Stored string in redis:: Mongodb
Stored string in redis:: Redis
List of stored keys:: tutorial-name
List of stored keys:: tutorial-list

4. Source Files

5. References