Example code in Java that USES Jedis to manipulate Redis

  • 2020-05-26 09:14:23
  • OfStack

jedis-2.1.0.jar is required to operate Redis using Java. Download from jedis-2.1.0.jar

If you need to use the Redis connection pool, commons-pool-1.5.4.jar, commons-pool-1.5.4.jar


package com.test;

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

import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;

public class TestRedis {
  private Jedis jedis; 
  
  @Before
  public void setup() {
    // The connection redis The server, 192.168.0.100:6379
    jedis = new Jedis("192.168.0.100", 6379);
    // Authority certification 
    jedis.auth("admin"); 
  }
  
  /**
   * redis Store string 
   */
  @Test
  public void testString() {
    //----- Add data ---------- 
    jedis.set("name","xinxin");// to key-->name Put the value-->xinxin 
    System.out.println(jedis.get("name"));// Execution results: xinxin 
    
    jedis.append("name", " is my lover"); // Joining together 
    System.out.println(jedis.get("name")); 
    
    jedis.del("name"); // Delete a key 
    System.out.println(jedis.get("name"));
    // Set multiple key-value pairs 
    jedis.mset("name","liuling","age","23","qq","476777XXX");
    jedis.incr("age"); // add 1 operation 
    System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
    
  }
  
  /**
   * redis operation Map
   */
  @Test
  public void testMap() {
    //----- Add data ---------- 
    Map<String, String> map = new HashMap<String, String>();
    map.put("name", "xinxin");
    map.put("age", "22");
    map.put("qq", "123456");
    jedis.hmset("user",map);
    // Take out the user In the name , execution result :[minxr]--> Notice the result is 1 A generic List 
    // The first 1 Three parameters are stored redis In the map The object's key , followed by put in map Of an object in key Behind, key Can be more than one, is a variable parameter  
    List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
    System.out.println(rsmap); 
 
    // delete map Some key value in  
    jedis.hdel("user","age");
    System.out.println(jedis.hmget("user", "age")); // Because it was deleted, it returned null 
    System.out.println(jedis.hlen("user")); // return key for user The number of values stored in a key 2 
    System.out.println(jedis.exists("user"));// If there is a key for user The record of   return true 
    System.out.println(jedis.hkeys("user"));// return map All in the object key 
    System.out.println(jedis.hvals("user"));// return map All in the object value 
 
    Iterator<String> iter=jedis.hkeys("user").iterator(); 
    while (iter.hasNext()){ 
      String key = iter.next(); 
      System.out.println(key+":"+jedis.hmget("user",key)); 
    } 
  }
  
  /** 
   * jedis operation List 
   */ 
  @Test 
  public void testList(){ 
    // Before you start, remove everything  
    jedis.del("java framework"); 
    System.out.println(jedis.lrange("java framework",0,-1)); 
    // Be the first to key java framework In the store 3 The data  
    jedis.lpush("java framework","spring"); 
    jedis.lpush("java framework","struts"); 
    jedis.lpush("java framework","hibernate"); 
    // I'm going to pull out all the data jedis.lrange I'm taking it out by range,  
    //  The first 1 One is key In the first 2 One is the starting position, one 3 One is the end position, jedis.llen To obtain the length of the  -1 Means get all  
    System.out.println(jedis.lrange("java framework",0,-1)); 
    
    jedis.del("java framework");
    jedis.rpush("java framework","spring"); 
    jedis.rpush("java framework","struts"); 
    jedis.rpush("java framework","hibernate"); 
    System.out.println(jedis.lrange("java framework",0,-1));
  } 
  
  /** 
   * jedis operation Set 
   */ 
  @Test 
  public void testSet(){ 
    // add  
    jedis.sadd("user","liuling"); 
    jedis.sadd("user","xinxin"); 
    jedis.sadd("user","ling"); 
    jedis.sadd("user","zhangxinxin");
    jedis.sadd("user","who"); 
    // remove noname 
    jedis.srem("user","who"); 
    System.out.println(jedis.smembers("user"));// Get all the entries value 
    System.out.println(jedis.sismember("user", "who"));// judge  who  Whether it is user Elements of a set  
    System.out.println(jedis.srandmember("user")); 
    System.out.println(jedis.scard("user"));// Returns the number of elements in the collection  
  } 
 
  @Test 
  public void test() throws InterruptedException { 
    //jedis  The sorting  
    // Notice here rpush and lpush is List In the operation. is 1 Two two-way linked lists (but in terms of performance)  
    jedis.del("a");// Clear the data first, then add the data for testing  
    jedis.rpush("a", "1"); 
    jedis.lpush("a","6"); 
    jedis.lpush("a","3"); 
    jedis.lpush("a","9"); 
    System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1] 
    System.out.println(jedis.sort("a")); //[1, 3, 6, 9] // Enter the sorted results  
    System.out.println(jedis.lrange("a",0,-1)); 
  } 
  
  @Test
  public void testRedisPool() {
    RedisUtil.getJedis().set("newname", " Chinese test ");
    System.out.println(RedisUtil.getJedis().get("newname"));
  }
}

Redis connection pool:


package com.test;

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

public final class RedisUtil {
  
  //Redis The server IP
  private static String ADDR = "192.168.0.100";
  
  //Redis The port number 
  private static int PORT = 6379;
  
  // Access to the password 
  private static String AUTH = "admin";
  
  // The maximum number of connection instances available, default is 8 ; 
  // If I assign a value of -1 , is unrestricted; if pool Has been allocated maxActive a jedis Instance, then at this point pool The status of exhausted( Run out of ) . 
  private static int MAX_ACTIVE = 1024;
  
  // control 1 a pool How many states are there at most idle( free ) the jedis The default value is the same 8 . 
  private static int MAX_IDLE = 200;
  
  // The maximum time to wait for an available connection in milliseconds, with a default value of -1 , which means never time out. If the wait time is exceeded, it is thrown directly JedisConnectionException ; 
  private static int MAX_WAIT = 10000;
  
  private static int TIMEOUT = 10000;
  
  // in borrow1 a jedis Example, whether to advance validate Operation; If it is true , is obtained jedis Instances are available; 
  private static boolean TEST_ON_BORROW = true;
  
  private static JedisPool jedisPool = null;
  
  /**
   *  Initialize the Redis The connection pool 
   */
  static {
    try {
      JedisPoolConfig config = new JedisPoolConfig();
      config.setMaxActive(MAX_ACTIVE);
      config.setMaxIdle(MAX_IDLE);
      config.setMaxWait(MAX_WAIT);
      config.setTestOnBorrow(TEST_ON_BORROW);
      jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  /**
   *  To obtain Jedis The instance 
   * @return
   */
  public synchronized static Jedis getJedis() {
    try {
      if (jedisPool != null) {
        Jedis resource = jedisPool.getResource();
        return resource;
      } else {
        return null;
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  
  /**
   *  The release of jedis resources 
   * @param jedis
   */
  public static void returnResource(final Jedis jedis) {
    if (jedis != null) {
      jedisPool.returnResource(jedis);
    }
  }
}


Related articles: