2022-1-28 Redis Java client Jedis/Lettuse

1. Open remote connection

Redis does not support remote connection by default and needs to be opened manually.
Enter redis conf

  • Comment out the following bind ing

  • Uncomment and set password (enable password verification)

    requirepass 123456

  • Then start redis

2. Jedis

  1. Create a normal Maven project
  2. Add Jedis dependency
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.0.1</version>
</dependency>
  1. Create test method
public class MyJedis {
    public static void main(String[] args) {
        //1. The Jedis object is constructed. Because the default port 6379 is used, the port can not be configured
        Jedis jedis = new Jedis("192.168.xx.xx",6379);
        //2. Password authentication
        jedis.auth("123456");
        //3. Test whether the connection is successful (ping)
        String ping=jedis.ping();
        //4. The return of pong indicates that the connection is successful
        System.out.println(ping);
    }
}

The connection is successful when PONG is output:

If the connection is not successful - confirm that the configuration is correct, and the redis service has been opened - or not - restart may be the best way

In jedis, because the API of the method is highly consistent with the redis command, the method in jedis can be used directly.

Connection pool

In practical applications, jedis instances are generally obtained through the connection pool. Because jedis objects are not thread safe, when we use jedis objects, we obtain jedis from the connection pool and return them to the connection pool after use.

public class JedisPoolTest {
    public static void main(String[] args) {
        //1. Construct a Jedis connection pool
        JedisPool pool = new JedisPool("192.168.", 6379);
        //2. Get Jedis from the connection pool; connect
        Jedis jedis = pool.getResource();
        //3. Jedis operation
        jedis.auth("123456");
        String ping = jedis.ping();
        System.out.println(ping);
        
        //4. Return the connection
        jedis.close();

    }
}

If an exception occurs in step 3, the connection cannot be closed, the connection cannot be returned, and the connection is permanently occupied.
So optimize – finally

package org.kk.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @program: jedis
 * @description:
 * @author: zjx
 * @create: 2022-01-28 21:39
 **/
public class JedisPoolTest {
    public static void main(String[] args) {
        Jedis jedis = null;

            //1. Construct a Jedis connection pool
            JedisPool pool = new JedisPool("192.168.", 6379);
            //2. Get Jedis from the connection pool; connect
            jedis = pool.getResource();
            //3. Jedis operation
        try {
            jedis.auth("123456");
            String ping = jedis.ping();
            System.out.println(ping);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4. Return the connection
            if(jedis!=null){
                jedis.close();
            }
        }



    }
}

Re Optimization:
Using jdk1 The try with resource feature in 7 can transform the above code:

package org.kk.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @program: jedis
 * @description:
 * @author: zjx
 * @create: 2022-01-28 21:39
 **/
public class JedisPoolTest {
    public static void main(String[] args) {
        JedisPool pool = new JedisPool("192.168.", 6379);
        try(Jedis jedis=pool.getResource()) {
            jedis.auth("123456");
            String ping = jedis.ping();
            System.out.println(ping);
        }
        
    }
}

It still seems unreliable... The above code cannot implement strong constraints. We can make further improvements:

Write an interface, and then implement it when it is called.

First define the interface:

package org.kk.jedis;

import redis.clients.jedis.Jedis;

public interface CallWithJedis {
    void call(Jedis jedis);
    //Make an implementation class for this interface, and pass Jedis in the implementation class

}

Then implement Redis:

package org.kk.jedis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @program: jedis
 * @description:
 * @author: zjx
 * @create: 2022-01-28 22:19
 **/
public class Redis {
    private JedisPool pool;

    public Redis(){ //Initialize
        GenericObjectPoolConfig config=new GenericObjectPoolConfig();
        pool=new JedisPool(config,"192.168.10.14",6379);
        //Or write the full parameter timeout and password
    }

    public void execute(CallWithJedis callWithJedis){
        try(Jedis jedis=pool.getResource())
        {
            callWithJedis.call(jedis);
        }
    }
}

Test:

    public static void main(String[] args) {
        Redis redis = new Redis();
        redis.execute(jedis -> {
            jedis.auth("123456");
            System.out.println(jedis.ping());
        });
    }

Some configurations:

  public Redis(){ //Initialize
        GenericObjectPoolConfig config=new GenericObjectPoolConfig();
        config.setMaxIdle(300);//Maximum free number of connection pool
        config.setMaxTotal(1000);//maximum connection
        config.setMaxWaitMillis(10000);//The maximum waiting time for connection is - 1, which means there is no limit
        config.setTestOnBorrow(true);//Check validity when idle
        pool=new JedisPool(config,"192.168.10.14",6379);
    }

3. Lettuce

github search.

Comparison between Lettuce and Jedis:

  1. Jedis is directly connected to Redis in the process of implementation. Sharing one jedis instance among multiple threads is thread unsafe. If you want to use jedis in a multithreaded scenario, you have to use the connection pool. In this way, each thread has its own jedis instance and requires many physical resources
  2. Lettuse is built based on the currently popular Netty NIO framework, so it overcomes the problem of thread insecurity in Jedis, supports synchronous, asynchronous and responsive calls, and multiple threads can share a connection instance.

Using Lettuse, create a normal maven project and add dependencies.
Basic Use
Note: the password is written in the connection

RedisClient client = RedisClient.create("redis://password@192.168.");
StatefulRedisConnection<String, String> connection = client.connect();
RedisStringCommands sync = connection.sync();
sync.set("key","123");
String value = sync.get("key");

Keywords: Java Redis Cache

Added by mpar612 on Wed, 02 Feb 2022 17:11:59 +0200