Redis Combat-jedis Usage Guide

Source: Internet
Author: User
Tags auth redis serialization redis server
Overview

Redis is an open-source, efficient key-value storage system and is the most common form of nosql. Redis is ideal for caching systems, and a detailed introduction to Redis can be seen in the official Redis documentation.

Redis supports multiple language calls, and the official Java version of the client is Jedis, which is very powerful and stable, supporting transactions, pipelines, and Jedis implementations. The operation of our Redis data can be done through Jedis.

Using tutorials
1. Configure MAVEN Dependencies

<dependency>
    <groupId>redis.clients</groupId>
    <artifactid>jedis</artifactid >
    <version>2.8.0</version>
    <type>jar</type>
    <scope>compile</ Scope>
</dependency>
Jedis Thread safety issues

First, it is important to note that a single Jedis instance is not thread-safe and you should use Jedispool in a multithreaded environment.

Using Jedis in a multithreaded environment

You shouldn ' t use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which Leads to strange errors as well. A single Jedis instance are not threadsafe! To avoid these problems, your should use Jedispool, which is a threadsafe pool of network connections. You can use the pool to reliably create several Jedis instances and given you return the Jedis instance to the pool when done . This can overcome those strange errors and achieve great performance.

Initialize Pool

Jedispool pool = new Jedispool (new Jedispoolconfig (), "localhost");

Jedispool is thread-safe and you can save it as a static variable.

To ensure that the Jedis is bound to be closed, we can use the Try-finally statement as follows:

Jedis Jedis = null;
try {
  Jedis = Pool.getresource ();
  ... do stuff here ...
  for example jedis.set ("foo", "Bar");
  String foobar = jedis.get ("foo");
  Jedis.zadd ("Sose", 0, "car"); Jedis.zadd ("Sose", 0, "bike"); 
  Set<string> sose = Jedis.zrange ("Sose", 0,-1);
} Finally {
  if (Jedis! = null) {
    jedis.close ();}
}
... when closing your application:
Pool.destroy ();

Before introducing the use of the Jedis API, let's use a singleton pattern to jedispool a package with the following code:

Package com.ricky.codelab.redis.sample.pool;
Import java.io.IOException;

Import java.util.Properties;

Import Org.apache.commons.lang3.StringUtils;

Import Com.ricky.codelab.redis.sample.util.PropertyUtils;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig;
    public class Jedispoolmanager {Private volatile static Jedispoolmanager manager;

    Private final Jedispool pool; Private Jedispoolmanager () {try {//load Redis configuration Properties props = Propertyutils.load ("Red

            Is.properties ");

            Create Jedis pool configuration instance jedispoolconfig config = new Jedispoolconfig ();
            Set Pool configuration entry value String maxtotal = Props.getproperty ("Redis.pool.maxTotal", "4");

            Config.setmaxtotal (Integer.parseint (maxtotal));
            String Maxidle = Props.getproperty ("Redis.pool.maxIdle", "4");

            Config.setmaxidle (Integer.parseint (Maxidle)); String MinidlE = Props.getproperty ("Redis.pool.minIdle", "1");

            Config.setminidle (Integer.parseint (Minidle));
            String Maxwaitmillis = Props.getproperty ("Redis.pool.maxWaitMillis", "1024");

            Config.setmaxwaitmillis (Long.parselong (Maxwaitmillis));
            String Testonborrow = Props.getproperty ("Redis.pool.testOnBorrow", "true");

            Config.settestonborrow ("true". Equals (Testonborrow));
            String Testonreturn = Props.getproperty ("Redis.pool.testOnReturn", "true");

            Config.settestonreturn ("true". Equals (Testonreturn));
            String Server = Props.getproperty ("Redis.server");
            if (stringutils.isempty (server)) {throw new IllegalArgumentException ("Jedispool redis.server is empty!");
            } string[] Host_arr = Server.split (",");
            if (host_arr.length>1) {throw new IllegalArgumentException ("Jedispool redis.server length > 1"); } String[] arr = Host_arr[0].split (":");
            Instantiate the Jedis pool System.out.println ("***********init jedispool***********") according to the configuration;

            System.out.println ("host->" +arr[0]+ ",port->" +arr[1]);

        Pool = new Jedispool (config, arr[0], Integer.parseint (arr[1]));
        } catch (IOException e) {throw new IllegalArgumentException ("Init jedispool error", E); }} public static Jedispoolmanager Getmgr () {if (manager = = null) {synchronized (jedispool
                Manager.class) {if (manager = = null) {manager = new Jedispoolmanager ();
    }}} return manager;
    } public Jedis GetResource () {return pool.getresource ();
    } public void Destroy () {//when closing your Application:pool.destroy ();
    } public void Close () {pool.close ();
 }
}

Redis.properties as follows:

# Redis Server IP and Port
redis.server=172.18.19.208:6379

# Redis pool
redis.pool.maxtotal=20
redis.pool.maxidle=10
redis.pool.minidle=1
redis.pool.maxwaitmillis=60000
redis.pool.testonborrow= True
redis.pool.testonreturn=true

With the Jedispoolmanager class, the template code for manipulating Jedis is simplified as follows:

Jedis Jedis = null;
try {
      Jedis = Jedispoolmanager.getmgr (). getresource ();    jedis.auth ("Hello");
} Finally {
      if (Jedis! = null) {
        jedis.close ();}
}
... when closing your application:
jedispoolmanager.getmgr (). Destroy ();
Basic Usage
Package com.ricky.codelab.redis.sample;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;

Import Java.util.Set;

Import Com.ricky.codelab.redis.sample.pool.JedisPoolManager;

Import Redis.clients.jedis.Jedis;
        public class Redisdemo {public static void main (string[] args) {Jedis Jedis = null;

          try {Jedis = Jedispoolmanager.getmgr (). getresource ();//Jedis.auth ("Hello");
          Simple Key-value Jedis.set ("Redis", "Myredis");

          System.out.println (Jedis.get ("Redis"));   
          Jedis.append ("Redis", "Yourredis");

          Jedis.append ("MQ", "RabbitMQ");
          incr String PV = Jedis.set ("PV", "0");
          System.out.println ("PV:" +PV);
          JEDIS.INCR ("PV");
          Jedis.incrby ("PV", 10);

          System.out.println ("PV:" +PV);
          Mset jedis.mset ("FirstName", "Ricky", "LastName", "Fung"); System.out.println (Jedis.mget ("FirstName", "LastName"));
          Map map<string,string> cityMap = new hashmap<string,string> ();
          Citymap.put ("Beijing", "1");

          Citymap.put ("Shanghai", "2");
          Jedis.hmset ("City", CityMap);
          System.out.println (Jedis.hget ("City", "Beijing"));
          System.out.println (Jedis.hlen ("City"));

          System.out.println (Jedis.hmget ("City", "Beijing", "Shanghai"));
          List Jedis.lpush ("hobbies", "reading");
          Jedis.lpush ("Hobbies", "basketball");

          Jedis.lpush ("Hobbies", "shopping");
          List<string> Hobbies = Jedis.lrange ("Hobbies", 0,-1);

          SYSTEM.OUT.PRINTLN ("Hobbies:" +hobbies);

          Jedis.del ("hobbies");
          Set Jedis.sadd ("name", "Ricky");
          Jedis.sadd ("name", "Kings");

          Jedis.sadd ("name", "Demon");
          SYSTEM.OUT.PRINTLN ("Size:" +jedis.scard ("name"));
          System.out.println ("exists:" +jedis.sismember ("name", "Ricky")); SysteM.out.println (String.Format ("All Members:%s", Jedis.smembers ("name"));
          System.out.println (String.Format ("Rand member:%s", Jedis.srandmember ("name"));

          Remove Jedis.srem ("name", "Demon");
          Hset Jedis.hset ("Address", "Country", "CN");
          Jedis.hset ("Address", "province", "BJ");
          Jedis.hset ("Address", "City", "Beijing");

          Jedis.hset ("Address", "District", "Chaoyang");
          System.out.println ("City:" +jedis.hget ("Address", "City");
          System.out.println ("Keys:" +jedis.hkeys ("Address"));

          System.out.println ("Values:" +jedis.hvals ("Address")); 
          Zadd Jedis.zadd ("gift", 0, "car"); 
          Jedis.zadd ("Gift", 0, "bike");
          set<string> gift = Jedis.zrange ("Gift", 0,-1);

        System.out.println ("Gift:" +gift);
          } finally {if (Jedis! = null) {jedis.close (); }}///... when closing your applicatioN:jedispoolmanager.getmgr (). Destroy ();
 }

}

In addition, we can insert a string in addition to using Redis.clients.jedis.Jedis.set (string key, String value), You can also use Redis.clients.jedis.BinaryJedis.set (byte[] key, byte[] value) to save our custom Pojo class with the following code:

Package com.ricky.codelab.redis.sample;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable;
Import Com.ricky.codelab.redis.sample.pool.JedisPoolManager;

Import Redis.clients.jedis.Jedis;

        public class Redispojodemo {public static void main (string[] args) throws IOException, ClassNotFoundException {
        Jedis Jedis = null;

            try {Jedis = Jedispoolmanager.getmgr (). GetResource ();
            person person = new Person ("Ricky", 27);

            Serialized byte[] ByteArray = serialize (person);

            Set Jedis.set ("Ricky". GetBytes (), ByteArray);
            Get ByteArray = Jedis.get ("Ricky". GetBytes ());

            Deserialization of person = deserialize (ByteArray);

        SYSTEM.OUT.PRINTLN (person);
           } finally {if (Jedis! = null) {     Jedis.close ();
    }}///... when closing your APPLICATION:JEDISPOOLMANAGER.GETMGR (). Destroy (); } public static person deserialize (byte[] byteArray) throws ClassNotFoundException, ioexception{objectinputs
        Tream ois = null;
            try {bytearrayinputstream Bais = new Bytearrayinputstream (ByteArray);
            OIS = new ObjectInputStream (Bais);
        return (person) ois.readobject ();
        } finally {ois.close ();
        }} public static byte[] Serialize (person person) throws ioexception{Bytearrayoutputstream BAOs = null;
        ObjectOutputStream oos = null;
            try {BAOs = new Bytearrayoutputstream ();
            Oos = new ObjectOutputStream (BAOs);
            Oos.writeobject (person);

            Oos.flush ();

        return Baos.tobytearray ();
            } finally {oos.close ();
        Baos.close (); }}} class person ImplemEnts Serializable {/** * */private static final long serialversionuid = 1L;
    private String name;

    private int age;
        Public person () {} public person (String name, int age) {this.name = name;
    This.age = age;
    } public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } public int Getage () {return age;
    public void Setage (int.) {this.age = age;
    } @Override Public String toString () {return ' person [name= + name + ', age= ' + Age + '] ";
 }
}

There is a need for a Java serialization mechanism, a built-in serialization mechanism for Java, and of course the use of efficient serialization mechanisms provided by third parties, such as Kryo, Hessian, Protostuff, and so on. Advanced Usage

1. Transaction (Transactions)
The so-called transaction, that is, a continuous operation, whether

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.