Redis getting started - Jedis operating redis

This article mainly introduces the use of redis command line, the software version used: Java 1.8.0_191,Redis 5.0.8,Jedis 3.3.0.

1. Introduce dependency

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
</dependency>

2. Basic operation

package com.inspur.demo.general.redis;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Using jedis to realize the basic operation of redis
 */
public class JedisBaseCase {
    private Jedis jedis;

    @Before
    public void before() {
        jedis = new Jedis("10.49.196.10");
        jedis.auth("123456");
    }

    @After
    public void after() {
        jedis.close();
    }

    /***********************************Key begin*****************************/
    /**
     * Clear all key s
     */
    @Test
    public void flushAll() {
        String status = jedis.flushAll();
        System.out.println(status);
    }

    /**
     * Rename key
     */
    @Test
    public void rename() {
        String status = jedis.rename("name", "name2");
        System.out.println(status);
    }

    /**
     * Rename key, only executed when the new key does not exist
     * Return value:
     * 1: oldKey Renamed
     * 0: newKey Already exists
     */
    @Test
    public void renamenx() {
        long status = jedis.renamenx("name", "name3");
        System.out.println(status);
    }

    /**
     * Set the expiration time of key in seconds
     * Return value:
     * 1: Expiration time set successfully
     * 0: key non-existent
     */
    @Test
    public void expired() {
        long status = jedis.expire("name", 100);
        System.out.println(status);
    }

    /**
     * Set the expiration time of the key, which is the number of seconds from the epoch (that is, 00:00:00 GMT, January 1, 1970).
     * Return value:
     * 1: Expiration time set successfully
     * 0: key non-existent
     */
    @Test
    public void expiredAt() {
        long status = jedis.expireAt("name", System.currentTimeMillis()/1000 + 100);
        System.out.println(status);
    }

    /**
     * Query the expiration time of key, in seconds
     * Return value:
     *  -1: No expiration time
     *  -2: Indicates that the key does not exist
     *  Other: expiration time of key
     */
    @Test
    public void ttl() {
        long time = jedis.ttl("name");
        System.out.println(time);
    }

    /**
     * Persistent key
     * Return value:
     *  1: It's been sustained
     *  0: key non-existent
     */
    @Test
    public void persist() {
        long state = jedis.persist("name");
        System.out.println(state);
    }


    /**
     * Delete key
     * Return value:
     * Number of key s deleted successfully
     * 0 Indicates that no key exists
     */
    @Test
    public void del() {
        long state = jedis.del("name", "name1");
        System.out.println(state);
    }
    /***********************************Key end*******************************/
    /***********************************String begin***************************/
    @Test
    public void set() {
        String status = jedis.set("name", "mayun");
        System.out.println(status);
    }

    /**
     * Add records with expiration time
     */
    @Test
    public void setex() {
        String status = jedis.setex("name", 100, "mayun");
        System.out.println(status);
    }

    /**
     * Add a record, insert only when the given key does not exist
     * Return value:
     * 1: key set successfully
     * 0: Can not exist
     */
    @Test
    public void setnx() {
        long code = jedis.setnx("name", "mayun");
        System.out.println(code);
    }

    @Test
    public void mset() {
        String status = jedis.mset("name", "mayun", "age", "50");
        System.out.println(status);
    }

    @Test
    public void get() {
        String value = jedis.get("name");
        System.out.println(value);
    }

    @Test
    public void mget() {
        List<String> value = jedis.mget("name", "age");
        System.out.println(value);
    }

    /**
     * Subtract the value corresponding to the key from the specified value. This method is only available when the value can be converted to a number
     * Returns the subtracted value
     */
    @Test
    public void decrBy() {
        long value = jedis.decrBy("salary", 10);
        System.out.println(value);
    }

    /**
     * Add the value corresponding to the key to the specified value. This method is only available when the value can be converted to a number
     * Returns the added value
     *
     * <b>Can be used as a way to get a unique id</b>
     */
    @Test
    public void incrBy() {
        long value = jedis.incrBy("salary", 10);
        System.out.println(value);
    }

    /**
     * Set the value of Key and return the old value
     */
    @Test
    public void getSet() {
        String value = jedis.getSet("name", "pony ");
        System.out.println(value);
    }

    /***********************************String end***************************/

    /***********************************list begin***************************/
    /**
     * Insert one or more values into the list header
     * Returns the number of data inserted into the queue
     */
    @Test
    public void lpush() {
        Long num = jedis.lpush("list", "a", "b", "c");
        System.out.println(num);
    }

    /**
     * Inserts one or more values at the end of the list
     * Returns the number of data inserted into the queue
     */
    @Test
    public void rpush() {
        Long num = jedis.rpush("list", "a", "b", "c");
        System.out.println(num);
    }

    /**
     * Inserts one or more values into the existing list header
     * Returns the number of data inserted into the queue
     */
    @Test
    public void lpushx() {
        Long num = jedis.lpushx("list", "1", "2", "3");
        System.out.println(num);
    }

    /**
     * Inserts one or more values at the end of an existing list
     * Returns the number of data inserted into the queue
     */
    @Test
    public void rpushx() {
        Long num = jedis.rpushx("list", "1", "2", "3");
        System.out.println(num);
    }

    /**
     * Return data within the specified range of the list
     */
    @Test
    public void lrange() {
        List<String> list = jedis.lrange("list", 0, 5);
        System.out.println(list);
    }
    /***********************************list end***************************/

    /***********************************hash begin***************************/
    /**
     * Return the number of newly added fields. If all fields exist, update and return 0
     */
    @Test
    public void hset() {
        HashMap<String, String> values = new HashMap<>();
        values.put("age", "50");
        values.put("sex", "male");
        long code = jedis.hset("mayun", values);
        System.out.println(code);
        code = jedis.hset("mayun", "address", "Hangzhou");
        System.out.println(code);
    }

    @Test
    public void hgetAll() {
        Map<String, String> value = jedis.hgetAll("mayun");
        System.out.println(value);
    }

    /**
     * Add the value corresponding to the field to the specified value. This method is only available when the value can be converted to a number
     * Return the increased value
     */
    @Test
    public void hincrBy() {
        long value = jedis.hincrBy("mayun", "age", 1);
        System.out.println(value);
    }

    /***********************************hash begin***************************/

    /***********************************set begin***************************/
    /**
     * Add elements to set
     * Successfully increased the number of elements, if all exist, return 0
     */
    @Test
    public void sadd() {
        long value = jedis.sadd("set", "a", "b");
        System.out.println(value);
    }

    /**
     * Remove elements from set
     * 1: Removed successfully
     * 0: Element does not exist
     */
    @Test
    public void srem() {
        long value = jedis.srem("set", "a");
        System.out.println(value);
    }

    /**
     * Get all elements in the set
     */
    @Test
    public void smembers() {
        Set<String> value = jedis.smembers("set");
        System.out.println(value);
    }

    /***********************************set begin***************************/

    /***********************************sorted set begin***************************/
    /**
     * Add elements to the sorted set
     * 1: Successfully added
     * 0: Element already exists
     */
    @Test
    public void zadd() {
        long value = jedis.zadd("sortedset", 1, "a");
        System.out.println(value);
        value = jedis.zadd("sortedset", 2, "b");
        System.out.println(value);
    }

    /**
     * Remove elements from sorted set
     * 1: Removed successfully
     * 0: Element does not exist
     */
    @Test
    public void zrem() {
        long value = jedis.zrem("sortedset", "a");
        System.out.println(value);
    }

    /**
     * Get all elements in the set
     */
    @Test
    public void zrange() {
        Set<String> value = jedis.zrange("sortedkey", 0, 5);
        System.out.println(value);
    }
    /***********************************sorted set end***************************/

    /***********************************hyper begin***************************/
    /**
     * Add specified element to HyperLogLog
     * Returns the number of successful days, or 0 if all elements already exist
     */
    @Test
    public void pfadd() {
        long code = jedis.pfadd("hyper", "a", "b", "d");
        System.out.println(code);
    }

    /**
     * Returns the cardinality estimate for the given HyperLogLog
     */
    @Test
    public void pfcount() {
        long value = jedis.pfcount("hyper");
        System.out.println(value);
    }
    /***********************************hyper end***************************/
}

3. Advanced operations

package com.inspur.demo.general.redis;

import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * Advanced operations
 */
public class JedisAdvancedCase {
    private JedisPoolConfig config;

    @Before
    public void before() {
        config = new JedisPoolConfig();
        config.setMaxWaitMillis(1000 * 30);//Maximum wait time when connections in the connection pool are exhausted
        config.setMaxTotal(20);//Maximum number of connections to the resource pool
        config.setMaxIdle(10);//Maximum number of idle connections in the resource pool
        config.setMinIdle(5);//Minimum number of idle connections in the resource pool
        config.setTestOnBorrow(true);//Whether to test when getting the connection instance, default false
        config.setTestWhileIdle(true);//Enable idle resource detection, default false
        config.setTimeBetweenEvictionRunsMillis(1000 * 10);//Detection cycle of idle resources
    }

    /**
     * Connection pool operation
     */
    @Test
    public void jedisPool() {
        JedisPool pool = new JedisPool(config, "10.49.196.10", 6379, 1000 * 10, "123456");
        //obtain Jedis Real series
        Jedis jedis = pool.getResource();
        System.out.println(jedis.get("name"));
        jedis.close();
        pool.close();
    }

    /**
     * Sentinel mode
     */
    @Test
    public void jedisSentinelPool() {
        Set<String> sentinels = new HashSet<>();
        sentinels.add("10.49.196.20:26379");
        sentinels.add("10.49.196.21:26379");
        sentinels.add("10.49.196.22:26379");
        JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, config, 1000 * 5, "123456");
        //obtain Jedis Real series
        Jedis jedis = pool.getResource();
        System.out.println(jedis.get("name"));
        jedis.close();
        pool.close();
    }

    /**
     * Cluster mode
     */
    @Test
    public void jedisCluster() {
        Set<HostAndPort> set = new HashSet<HostAndPort>();
        set.add(new HostAndPort("10.49.196.20", 7000));
        set.add(new HostAndPort("10.49.196.20", 7001));
        set.add(new HostAndPort("10.49.196.21", 7000));
        set.add(new HostAndPort("10.49.196.21", 7001));
        set.add(new HostAndPort("10.49.196.22", 7000));
        set.add(new HostAndPort("10.49.196.22", 7001));
        JedisCluster cluster = new JedisCluster(set, 1000 * 5, 1000 * 5, 5, "123456", config);

        //JedisCluster Basic operations and Jedis Very similar

        //key
        System.out.println("judge key Does it exist" + cluster.exists("name"));
        System.out.println("query key Expires on:" + cluster.ttl("name"));

        //String
        System.out.println("Set key value pair:" + cluster.set("name", "mahuateng"));
        System.out.println("obtain key Corresponding value:" + cluster.get("name"));

        //List
        System.out.println("Insert one or more values into the list header:" + cluster.lpush("list", "a", "b", "c"));
        System.out.println("Return data within the specified range of the list:" + cluster.lrange("list", 0, 5));

        //Hash
        HashMap<String, String> values = new HashMap<>();
        values.put("age", "50");
        values.put("sex", "male");
        System.out.println("stay hash Setting in field and value: " + cluster.hset("mayun", values));
        System.out.println("stay hash All properties and values in:" + cluster.hgetAll("mayun"));

        //set
        System.out.println("to set Add elements:" + cluster.sadd("set", "a", "b"));
        System.out.println("take set All elements in:" + cluster.smembers("set"));

        //sorted set
        System.out.println("to sorted set Add element 1:" + cluster.zadd("sortedset", 1, "a"));
        System.out.println("to sorted set Add element 2:" + cluster.zadd("sortedset", 2, "b"));
        System.out.println("obtain sorted set All elements in:" + cluster.zrange("sortedset",0, 5));

        //Cluster information
        System.out.println("Cluster node information:" + cluster.getClusterNodes());
        cluster.close();
    }
}

4. JedisPoolConfig parameter description

JedisPoolConfig is used to set the related properties of the connection pool. The specific parameters are as follows:

Parameter name explain Default proposal
maxTotal Maximum connections in resource pool 8  
maxIdle Maximum number of idle connections in the resource pool 8  
minIdle Minimum number of idle connections in the resource pool 0  
blockWhenExhausted Whether the caller will wait when the resource pool is exhausted. The following maxWaitMillis will not take effect until the value is true. true Default is recommended
maxWaitMillis The maximum wait time, in milliseconds, for the caller when the resource pool connection is exhausted. -1 (never time out) Default is not recommended
testOnBorrow Whether to ping the connection when borrowing the connection from the resource pool. Invalid connections detected will be removed. false When the traffic is large, it is recommended to set false to reduce the cost of a ping.
testOnReturn Whether to ping the connection when returning the connection to the resource pool. An invalid connection detected will be removed. false When the traffic is large, it is recommended to set false to reduce the cost of a ping.
jmxEnabled Whether JMX monitoring is enabled true It is recommended to open. Note that the application itself needs to be opened.
testWhileIdle Enable idle resource detection false Recommended on
timeBetweenEvictionRunsMillis Detection period of idle resources (in milliseconds) -1 (no detection) Recommended settings
minEvictableIdleTimeMillis The minimum idle time (in milliseconds) of the resource in the resource pool, at which point the idle resource will be removed. 1800000 (i.e. 30 minutes) It can be determined according to its own business. Generally, the default value is OK
numTestsPerEvictionRun When detecting idle resources, the number of resources is detected each time. 3 Fine tuning can be performed according to the number of application connections. If it is set to - 1, idle monitoring will be performed for all connections.

Tags: Java Jedis Redis Junit

Posted on Fri, 19 Jun 2020 22:43:17 -0400 by bsamson