Environment to prepare

JDK + Start redis service + IDEA (or Eclipse) + Jedis required JAR package

Jar + commons-pool2-2.6.2.jar

Or Maven dependencies:

<! -- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>
Copy the code

Before starting the Redis service, modify the Redis configuration file and the Linux firewall. Otherwise, the redis connection fails.

  • Comment the binding IP of bind.
# specify that Redis will only receive requests from this IP address, if not set, then all requests will be processed, preferably in a production environment
# bind 127.0.0.1
Copy the code
  • Turn off protected mode (or set password)
Redis protected mode is enabled by default. After enabled, the remote service requires a password to connect to the remote service. If no password is set and remote connection is required, the protected mode should be disabled
protected-mode no
Copy the code

If the protected mode is not disabled, you need to set a password. Jedis needs to connect to Redis with the password.

To set the password: config set requirepass 123456

Empty password (reboot required) : config set requirepass”

Obtain the password: config get requirepass

  • Turn off the firewall (or open redis service port)

Run the systemctl stop firewalld.service command to disable the firewall

Run the systemctl start firewalld.service command to start the firewall

You are advised not to disable the firewall. You need to enable the Redis service port (the firewall needs to be restarted).

Firewall – CMD –add-port=6379/ TCP

To disable the port: firewall-cmd –remove-port=6379/ TCP

Run the systemctl restart firewalld.service or firewall-cmd –reload command to restart the firewall

Test the connection

  • ifconfigCheck the Linux IP address, for example, mine is 192.168.64.129, and my Redis service startup port is 6379

  • No password (off protected mode)
public class PingTest {
    public static void main(String[] args) {
        // Parameters: IP address of redis server + redis startup port
        Jedis jedis = new Jedis("192.168.64.129".6379);
        // Result: PONGSystem.out.println(jedis.ping()); }}Copy the code
  • Have a password
public class PingTest {
    public static void main(String[] args) {
    	// Parameters: IP address of redis server + redis startup port
        JedisShardInfo jedisShardInfo = new JedisShardInfo("192.168.64.129".6379);
        // Set the redis password
        jedisShardInfo.setPassword("123456");
        Jedis jedis = jedisShardInfo.createResource();
        // Result: PONGSystem.out.println(jedis.ping()); }}Copy the code

When ping() returns PONG, the connection is successful.

Jedis commonly used API

Just list the parts, and the rest of the students try it on their own.

public class Test01 {
    public static void main(String[] args) {
        // Get the Jedis connection object
        JedisShardInfo jedisShardInfo = new JedisShardInfo("192.168.64.129".6379);
        jedisShardInfo.setPassword("123456");
        Jedis jedis = jedisShardInfo.createResource();

        // keys *
        Set<String> keys = jedis.keys("*");
        // Iterate over and print a key
        for (Iterator iterator = keys.iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            System.out.println(key);
        }
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        // exists k2
        System.out.println("jedis.exists====>" + jedis.exists("k2"));
        System.out.println(jedis.ttl("k1"));
        // get k1
        System.out.println(jedis.get("k1"));
        // set k4 k4_redis
        jedis.set("k4"."k4_redis");
        // mset str1 v1 str2 v2 str3 v3
        jedis.mset("str1"."v1"."str2"."v2"."str3"."v3");
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        // lpush mylist v1 v2 v3 v4 v5
        jedis.lpush("mylist"."v1"."v2"."v3"."v4"."v5");
        // lrange mylist 0 -1
        List<String> list = jedis.lrange("mylist".0, -1);
        // Iterate over the output myList list
        for (String element : list) {
            System.out.println(element);
        }
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        // sadd orders jd001
        jedis.sadd("orders"."jd001");
        // smembers orders
        Set<String> set1 = jedis.smembers("orders");
        // iterate over the output set unordered set
        for (Iterator iterator = set1.iterator(); iterator.hasNext(); ) {
            String string = (String) iterator.next();
            System.out.println(string);
        }
        // srem orders jd002
        jedis.srem("orders"."jd002");
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        // hset hash1 username lisi
        jedis.hset("hash1"."userName"."lisi");
        // hget hash1 username
        String hget = jedis.hget("hash1"."userName");
        Map<String, String> map = new HashMap<String, String>();
        map.put("telphone"."11012011933");
        map.put("address"."China");
        map.put("email"."[email protected]");
        // hmset hash2 telphone 11012011933 address China email 163
        jedis.hmset("hash2", map);
        // hmget hash2 telphone email
        List<String> result = jedis.hmget("hash2"."telphone"."email");
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        // zadd zset01 60 v1
        jedis.zadd("zset01".60d."v1");
        // zrange zset01 0 -1
        Set<String> s1 = jedis.zrange("zset01".0, -1);
        // Iterate over the output zset ordered set
        for(Iterator iterator = s1.iterator(); iterator.hasNext(); ) { String string = (String) iterator.next(); System.out.println(string); }}}Copy the code

Jedis transaction

public class TXTest01 {
    public static void main(String[] args) {
        JedisShardInfo jedisShardInfo = new JedisShardInfo("192.168.64.129".6379);
        jedisShardInfo.setPassword("123456");
        Jedis jedis = jedisShardInfo.createResource();

        // Monitor the key and discard the transaction if it needs to be moved
        // watch serialNum
        jedis.watch("serialNum");
        // set serialNum 1000
        jedis.set("serialNum"."1000");
        // unwatch
        // jedis.unwatch();

        // multi
        Transaction transaction = jedis.multi();// is executed as a command
        // set serialNum 1001
        transaction.set("serialNum"."1001");
        Response<String> response = transaction.get("serialNum");
        // lpush list01 a
        transaction.lpush("list01"."a");

        // exec
        transaction.exec();
        // discard
        //2 transaction.discard();

        // serialNum: 1000 (rolled back)
        System.out.println("serialNum:" + jedis.get("serialNum")); }}Copy the code

Jedis master slave replication

Start the Redis service on ports 6379 and 6380.

public class MSTest {
    public static void main(String[] args) {
        // Connect 6379 and 6380 with the protected mode turned off
        Jedis jedisM6379 = new Jedis("192.168.64.129".6379);
        Jedis jedisS6380 = new Jedis("192.168.64.129".6380);

        / / slaveof 192.168.64.129 6379
        jedisS6380.slaveof("192.168.64.129".6379);
        jedisM6379.set("k1"."v1");
        String result = jedisS6380.get("k1");
        // v1System.out.println(result); }}Copy the code

Jedis connection pool

Like database connection pool objects, reduces the frequency of creating or destroying database connection objects.

public class JedisPoolUtil {
    /** * database connection object */
    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil(a) {}/** * Double lock check singleton mode **@return* /
    public static JedisPool getJedisPoolInstance(a) {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    // Controls the number of jedis instances in a pool that are in idle state
                    poolConfig.setMaxIdle(32);
                    // Indicates the maximum wait time when borrow a Jedis instance. If the wait time is exceeded, JedisConnectionException is thrown directly
                    poolConfig.setMaxWaitMillis(1000);
                    // Check connection availability when obtaining a jedis instance (ping()); If true, the resulting Jedis instances are all available
                    poolConfig.setTestOnBorrow(true);
                    jedisPool = new JedisPool(poolConfig, "192.168.64.129".6379.2000."123456"); }}}return jedisPool;
    }

    /** * Close connection pool **@param jedisPool
     */
    public static void close(JedisPool jedisPool) {
        if (!jedisPool.isClosed()) {
            jedisPool.destroy();
        }
    }

    public static void main(String[] args) {
        JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
        JedisPool jedisPool2 = JedisPoolUtil.getJedisPoolInstance();

        // Test for singleton mode: true
        System.out.println(jedisPool == jedisPool2);

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            // PONG
            System.out.println(jedis.ping());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the connection pool objectJedisPoolUtil.close(jedisPool); }}}Copy the code

The connection pool configuration information is as follows:

JedisPool configuration parameters are mostly assigned by the corresponding items of JedisPoolConfig. MaxActive: Controls how many jedis instances can be allocated to a pool, using pool.getResource(); If the value is -1, there is no limit; If the pool has already allocated maxActive jedis instances, the pool is in the exhausted state. MaxIdle: Controls the number of jedis instances in a pool that are in idle state. Whenustedaction: Action to be taken when all jedis instances in the pool have been allocated. By default, there are three. When_hausted_fail --> NoSuchElementException is thrown when there is no jedis instance. When_hausted_block --> blocked, or JedisConnectionException thrown when maxWait is reached; When_hausted_grow --> indicates that a new jedis instance is created, i.e. maxActive is useless. MaxWait: Indicates the maximum wait time when borrow a Jedis instance. If the wait time is exceeded, JedisConnectionException is thrown directly. TestOnBorrow: Whether to check connection availability when obtaining a Jedis instance (ping()); If true, the resulting Jedis instances are all available; TestOnReturn: whether to check connection availability when a jedis instance is sent to the pool (ping()); TestWhileIdle: If true, an idle object evitor thread will scan the idle object. If validate fails, the object will be dropped from the pool. This item is only meaningful when timeBetweenEvictionRunsMillis is greater than 0; TimeBetweenEvictionRunsMillis: it means the idle object evitor between two scans to sleep the number of milliseconds; NumTestsPerEvictionRun: indicates the maximum number of objects scanned by the Idle Object evitor at a time. MinEvictableIdleTimeMillis: an object at least stay in the idle state of the shortest time, and then you can be idle object evitor scans and expelling; This item is only meaningful when timeBetweenEvictionRunsMillis is greater than 0; SoftMinEvictableIdleTimeMillis: on the basis of minEvictableIdleTimeMillis, joined at least minIdle target has had in the pool. If it is -1, Evicted does not expel any objects based on idle time. If minEvictableIdleTimeMillis > 0, then this setting meaningless, and is only meaningful when timeBetweenEvictionRunsMillis is greater than 0; When lifo: borrowObject returns an object, DEFAULT_LIFO (last in first out, i.e. the most frequently used queue similar to cache) is adopted. If it is False, it indicates FIFO queue. The default Settings of JedisPoolConfig for some parameters are as follows:  testWhileIdle=true minEvictableIdleTimeMills=60000 timeBetweenEvictionRunsMillis=30000 numTestsPerEvictionRun=-1Copy the code