Jedis the operation of Redis

Source: Internet
Author: User
Tags delete key memcached redis

Through a brief introduction of the previous article "Redis simple Use", this article mainly elaborates the five types of operation of Jedis to Redis: string, list, hash, set, ordered set. Jedisutil

The test cases here are run using JUNIT4, preparing the code as follows:

    private static final String ipaddr = "10.10.195.112";
    private static final int port = 6379;
    private static Jedis jedis= null;

    @BeforeClass public
    static void init ()
    {
        Jedis = Jedisutil.getinstance (). Getjedis (ipaddr, port);

    @AfterClass public
    static void Close ()
    {
        jedisutil.getinstance (). Closejedis (jedis,ipaddr, port);
    

Where Jedisutil is a simple package for Jedis, the code is as follows:

Import Org.apache.log4j.Logger;
Import Java.util.HashMap;

Import Java.util.Map;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig;

    public class Jedisutil {private Logger Logger = Logger.getlogger (This.getclass (). GetName ()); Private Jedisutil () {} private static class redisutilholder{private static final Jedisutil instance = new Jed
    Isutil ();
    public static Jedisutil getinstance () {return redisutilholder.instance;

    private static map<string,jedispool> maps = new hashmap<string,jedispool> ();
        private static Jedispool getpool (string ip, int port) {string key = ip+ ":" +port;
        Jedispool pool = null;
            if (!maps.containskey (key)) {Jedispoolconfig config = new Jedispoolconfig ();
            Config.setmaxactive (redisconfig.max_active);
            Config.setmaxidle (Redisconfig.max_idle); Config.setmaxwait (Redisconfig.max_wait);
            Config.settestonborrow (TRUE);

            Config.settestonreturn (TRUE);
            Pool = new Jedispool (config,ip,port,redisconfig.timeout);
        Maps.put (key, pool);
        else {pool = Maps.get (key);        
    } return pool;
        Public Jedis getjedis (String IP, int port) {Jedis Jedis = null;
        int count = 0;
            Do {try {Jedis = Getpool (ip,port). GetResource ();
                catch (Exception e) {logger.error ("Get Redis master1 failed!", e);
            Getpool (Ip,port). Returnbrokenresource (Jedis);
        } while (Jedis = = null && count<redisconfig.retry_num);
    return Jedis; } public void Closejedis (Jedis jedis, String IP, int port) {if (Jedis!= null) {Getpool (i
        P,port). Returnresource (Jedis);
  }  The maximum number of public class Redisconfig {//Available connection instances, the default value is 8;//If the assignment is-1, it is not restricted, and if the pool has already allocated maxactive Jedis instances, then the pool state is ex
    hausted (depleted).

    public static int max_active = 1024;
    Controls the maximum number of idle (idle) Jedis instances for a pool, and the default value is also 8.

    public static int max_idle = 200; The maximum time to wait for an available connection, in milliseconds, the default is-1, which means never timing out.

    If the wait time is exceeded, the jedisconnectionexception is thrown directly; public static int max_wait = 10000;

    public static int TIMEOUT = 10000;
public static int retry_num = 5; }
Key Action
    @Test public void TestKey () throws Interruptedexception {System.out.println ("Purge Data:" +jedis.flushdb ());
        System.out.println ("to determine whether a key exists:" +jedis.exists ("username"));
        System.out.println ("Add < ' username ', ' zzh ' > Key value pairs:" +jedis.set ("username", "Zzh"));
        System.out.println (jedis.exists ("name"));
        System.out.println ("Add < ' password ', ' Password ' > key value pairs:" +jedis.set ("password", "password"));
        System.out.print ("All keys in the system are as follows:");
        set<string> keys = Jedis.keys ("*");
        System.out.println (keys);
        System.out.println ("Delete key password:" +jedis.del ("password"));
        SYSTEM.OUT.PRINTLN ("Determine whether the key password exists:" +jedis.exists ("password"));
        SYSTEM.OUT.PRINTLN ("Set key username expires in 5s:" +jedis.expire ("username", 5));
        TimeUnit.SECONDS.sleep (2);
        System.out.println ("View the remaining lifetime of the key username:" +jedis.ttl ("username"));
        System.out.println ("Time to remove key username:" +jedis.persist ("username")); System.out.println ("View key username's remaining survivalTime: "+jedis.ttl" ("username"));
    System.out.println ("View the type of value stored by the key username:" +jedis.type ("username")); }

Output results:

Clear data: OK
to determine whether a key exists: false
Add < ' username ', ' zzh ' > key value pairs: OK
false
add < ' password ', ' password ' > Key-value pairs: OK
system All the keys are as follows: [username, password]
Delete key password:1
determine whether the key password exists: false
Set the expiration time of the key username to 5s:1
view key username remaining lifetime: 3
Remove key username lifetime: 1
View key username remaining lifetime: -1
View the type of the value stored by the key username: string
string Manipulation

Within Redis, a string can store three types of values: Byte string (byte string) integer floating-point byte string

    @Test public void TestString () throws Interruptedexception {jedis.flushdb ();
        System.out.println ("=========== Add Data ===========");
        System.out.println (Jedis.set ("Key1", "value1"));
        System.out.println (Jedis.set ("Key2", "value2"));
        System.out.println (Jedis.set ("Key3", "Value3"));
        System.out.println ("Delete key key2:" +jedis.del ("Key2"));
        SYSTEM.OUT.PRINTLN ("Get key Key2:" +jedis.get ("Key2"));
        System.out.println ("Modify Key1:" +jedis.set ("Key1", "value1changed"));
        System.out.println ("Get Key1 Value:" +jedis.get ("Key1"));
        System.out.println ("Add Value after Key3:" +jedis.append ("Key3", "End"));
        System.out.println ("Key3 Value:" +jedis.get ("Key3"));
        SYSTEM.OUT.PRINTLN ("Add multiple key values pairs:" +jedis.mset ("Key01", "value01", "key02", "Value02", "key03", "value03"));
        SYSTEM.OUT.PRINTLN ("Get multiple key value pairs:" +jedis.mget ("Key01", "key02", "key03"));
        SYSTEM.OUT.PRINTLN ("Get multiple key value pairs:" +jedis.mget ("Key01", "key02", "key03", "key04")); System.out.println ("Delete multiple key-value pairs:"+jedis.del (New string[]{" Key01 "," key02 "}));

        SYSTEM.OUT.PRINTLN ("Get multiple key value pairs:" +jedis.mget ("Key01", "key02", "key03"));
        Jedis.flushdb ();
        System.out.println ("=========== added key value to prevent overwriting original value ==============");
        System.out.println (Jedis.setnx ("Key1", "value1"));
        System.out.println (Jedis.setnx ("Key2", "value2"));
        System.out.println (Jedis.setnx ("Key2", "value2-new"));
        System.out.println (Jedis.get ("Key1"));

        System.out.println (Jedis.get ("Key2"));
        System.out.println ("=========== new key value pair and set valid time =============");
        System.out.println (Jedis.setex ("Key3", 2, "value3"));
        System.out.println (Jedis.get ("Key3"));
        TimeUnit.SECONDS.sleep (3);

        System.out.println (Jedis.get ("Key3")); System.out.println ("=========== Gets the original value, updates to the new value ==========");//getset is a atomic set this value and return the old value Comman
        D. System.out.println (Jedis.getset ("Key2", "Key2getset"));

   System.out.println (Jedis.get ("Key2"));     System.out.println ("The string that obtains the value of the Key2:" +jedis.getrange ("Key2", 2, 4)); }

Output results:

=========== Add data ===========
ok ok ok
Delete key key2:1
get key key2:null
modify Key1:ok
Get Key1 Value: value1changed add value after
Key3:9
Key3: value3end
add more than one key value pair: OK
gets multiple key pairs: [Value01, VALUE02, VALUE03]
get multiple key value pairs: [Value01, VALUE02, value03, null]
Delete multiple key-value pairs: 2
get multiple key-value pairs: [NULL, NULL, VALUE03]
= = ======= new key value to prevent overwriting the original value ==============
1
1
0
value1
value2
=========== add key value pairs and set valid time = = ==========
OK
value3
null
=========== Get the original value, update to the new value ==========
value2
key2getset
string that gets the value of the Key2: y2g

Memcached and Redis also have append operations, but memcached have prepend operations, which are not in Redis. integers and floating-point numbers

    @Test public void Testnumber ()
    {
        jedis.flushdb ();
        Jedis.set ("Key1", "1");
        Jedis.set ("Key2", "2");
        Jedis.set ("Key3", "2.3");
        System.out.println ("Key1 Value:" +jedis.get ("Key1"));
        System.out.println ("Key2 Value:" +jedis.get ("Key2"));
        System.out.println ("Key1 value plus 1:" +JEDIS.INCR ("Key1"));
        System.out.println ("Get Key1 Value:" +jedis.get ("Key1"));
        System.out.println ("Key2 value minus 1:" +jedis.decr ("Key2"));
        System.out.println ("Get Key2 Value:" +jedis.get ("Key2"));
        System.out.println ("Add key1 value to Integer 5:" +jedis.incrby ("Key1", 5));
        System.out.println ("Get Key1 Value:" +jedis.get ("Key1"));
        System.out.println ("Subtract Key2 value from integer 5:" +jedis.decrby ("Key2", 5));
        System.out.println ("Get Key2 Value:" +jedis.get ("Key2"));
    }

Output results:

Key1 value: 1
key2 Value: 2 key1 value
plus 1:2
get Key1 Value: 2 key2 value
minus 1:1
Gets the Key2 value: 1 adds the
key1 value to the integer 5:7
gets the value of Key1:7
Subtracts the Key2 value from the integer 5:-4
gets the Key2 value:-4

The

has this command in redis2.6 or above: Incrbyfloat, which is not supported in the value of the key store plus the floating-point number amount,jedis-2.1.0. List

@Test public void Testlist () {jedis.flushdb ();
    System.out.println ("=========== Add a list===========");
    Jedis.lpush ("Collections", "ArrayList", "Vector", "Stack", "HashMap", "Weakhashmap", "Linkedhashmap");
    Jedis.lpush ("Collections", "HashSet");
    Jedis.lpush ("Collections", "TreeSet");
    Jedis.lpush ("Collections", "TreeMap");
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));//-1 represents the penultimate element,-2 represents the penultimate element.
    System.out.println ("Collections interval 0-3 elements:" +jedis.lrange ("collections", 0, 3));
    System.out.println ("==============================="); Deletes the value specified by the list, the second parameter is the number of deletions (there are duplicates), and the value of the add is deleted first, similar to the stack System.out.println ("Delete the specified number of elements:" +jedis.lrem ("Collections", 2, "
    HashMap "));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));
    System.out.println ("Delete the elements outside the range of table 0-3 below:" +jedis.ltrim ("collections", 0, 3));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1)); System.out.println ("Collections list out stack (left):" +jediS.lpop ("collections"));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));
    System.out.println ("Collections add elements, from the right side of the list, and Lpush corresponding:" +jedis.rpush ("Collections", "Enummap"));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));
    System.out.println ("Collections list out stack (right side):" +jedis.rpop ("Collections"));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));
    System.out.println ("Modify collections Specify Subscript 1 content:" +jedis.lset ("Collections", 1, "linkedarraylist"));
    System.out.println ("Collections content:" +jedis.lrange ("collections", 0,-1));
    System.out.println ("===============================");
    System.out.println ("Length of Collections:" +jedis.llen ("Collections"));
    System.out.println ("Get the Element collections Subscript 2:" +jedis.lindex ("Collections", 2));
    System.out.println ("===============================");
    Jedis.lpush ("SortedList", "3", "6", "2", "0", "7", "4"); System.out.println ("SortedList sort before:" +jedis.lrange ("SortedList", 0,-1));
    System.out.println (Jedis.sort ("SortedList"));
System.out.println ("SortedList sort after:" +jedis.lrange ("SortedList", 0,-1));
 }

Output results:

=========== add a list=========== collections content: [TreeMap, TreeSet, HashSet, Linkedhashmap, Elements of Weakhashmap, HashMap, Stack, Vector, ArrayList] collections interval 0-3: [TreeMap, TreeSet, HashSet, Linkedhashmap] ======== ======================= deletes the specified number of elements: 1 collections: [TreeMap, TreeSet, HashSet, Linkedhashmap, Weakhashmap, Stack,
Vector, ArrayList] Delete elements outside the range of table 0-3: OK collections content: [TreeMap, TreeSet, HashSet, Linkedhashmap]
Collections list Stack (left): TreeMap collections content: [TreeSet, HashSet, Linkedhashmap] Collections add elements, from the right side of the list, and Lpush corresponds to: 4 Collections content: [TreeSet, HashSet, Linkedhashmap, Enummap] collections list out stack (right side): Enummap collections content: [TreeSet, HashSet, Linkedhashmap] Modify collections Specify subscript 1 content: OK collections: [TreeSet, Linkedarraylist, Linkedhashmap] ==========
===================== Collections Length: 3 Gets the element collections Subscript 2: Linkedhashmap =============================== SortedList sort before: [4, 7, 0, 2, 6, 3] [0, 2, 3, 4, 6, 7] SortedList sorted after: [4, 7, 0, 2, 6, 3] 

Redis also has blocked list popup commands and commands for moving elements between lists: Blpop, Brpop, Rpoplpush, Brpoplpush, and so on. collection (set)

    @Test public void Testset ()
    {
        jedis.flushdb ();
        System.out.println ("============ adds element ============ to the collection");
        System.out.println (Jedis.sadd) ("Eleset", "E1", "E2", "E4", "E3", "E0", "E8", "E7", "E5"));
        System.out.println (Jedis.sadd ("Eleset", "E6"));
        System.out.println (Jedis
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.