Java implements Message Queuing with Redis

Source: Internet
Author: User
Tags serialization sin

Application Scenarios
    • Why use Redis?
      Binary storage, Java serialization transfer, high IO connections, frequent connections
First, serialization

A Java serialization tool has been written to convert the object into a byte array and deserialize it into a Java object based on a byte array; The main use of Bytearrayoutputstream and bytearrayinputstream; Note: Each object that needs to be serialized must implement the Serializable interface;
The code is as follows:

1 package Utils; 2 Import java.io.*; 3/** 4  * Created by KINGLF on 2016/10/17.5 */  6 public class Objectutil {7     /** 8      * object to byte[] 9      * @p Aram Obj10      * @return11      * @throws IOException12      */13 public     static byte[] object2bytes (Object obj) Throws ioexception{14         Bytearrayoutputstream bo=new bytearrayoutputstream ();         ObjectOutputStream oo=new ObjectOutputStream (bo);         oo.writeobject (obj);         byte[] Bytes=bo.tobytearray ();         bo.close (); 19         oo.close (),         return bytes;21     }22     /**23      * byte[] turn to object      @param bytes25      * @ Return26      * @throws Exception27      */28 public     static Object bytes2object (byte[] bytes) throws exception{29         bytearrayinputstream in=new bytearrayinputstream (bytes);         ObjectInputStream sin=new ObjectInputStream (in);         return Sin.readobject ();     }33}
Second, message Class (implement Serializable interface)
Package Model;import java.io.serializable;/** * Created by KINGLF on 2016/10/17. */public class Message implements Serializable {    private static final long Serialversionuid = -389326121047047723l;
   private int id;    Private String content;    public Message (int ID, String content) {        this.id = ID;        this.content = content;    }    public int getId () {        return ID;    }    public void setId (int id) {        this.id = ID;    }    Public String getcontent () {        return content;    }    public void SetContent (String content) {        this.content = content;    }}
Third, the operation of Redis

Using Redis as a queue, we use the push and pop operations of the list in Redis;
Characteristics of the combined queue:
只允许在一端插入新元素只能在队列的尾部FIFO:先进先出原则Lpush 头入 (Rpop 尾出 ) or Rpush 尾入 (lpop) in Redis 头出 can meet the requirements, while the object for list drug push or pop in Redis only needs to be converted to byte[]
  java采用Jedis进行Redis的存储和Redis的连接池设置
On the code:

Package Utils;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import Redis.clients.jedis.jedispoolconfig;import java.util.list;import java.util.map;import java.util.Set;/** * Created by KINGLF on 2016/10/17.    */public class Jedisutil {private static String jedis_ip;    private static int jedis_port;    private static String Jedis_password;    private static Jedispool Jedispool;        static {//configuration Self-written configuration file resolution class, inherited from the properties configuration conf=configuration.getinstance ();        Jedis_ip=conf.getstring ("Jedis.ip", "127.0.0.1");        Jedis_port=conf.getint ("Jedis.port", 6379);        Jedis_password=conf.getstring ("Jedis.password", null);        Jedispoolconfig config=new jedispoolconfig ();        Config.setmaxactive (5000);        Config.setmaxidle (256);        Config.setmaxwait (5000L);        Config.settestonborrow (TRUE);        Config.settestonreturn (TRUE);        Config.settestwhileidle (TRUE); Config.setminevictableidletimemillis (60000L);        Config.settimebetweenevictionrunsmillis (3000L);        Config.setnumtestsperevictionrun (-1);    Jedispool=new Jedispool (config,jedis_ip,jedis_port,60000); /** * Get Data * @param key * @return */public static string get (String key) {string Value=nul        L        Jedis Jedis=null;            try{Jedis=jedispool.getresource ();        Value=jedis.get (key);            }catch (Exception e) {jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        }finally {Close (Jedis);    } return value;        } private static void Close (Jedis Jedis) {try{jedispool.returnresource (Jedis);                }catch (Exception e) {if (jedis.isconnected ()) {jedis.quit ();            Jedis.disconnect ();        }}} public static byte[] Get (byte[] key) {byte[] value = NULL;        Jedis Jedis = null; try {Jedis = Jedispool.getresoUrce ();        Value = Jedis.get (key);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return value;        } public static void set (Byte[] key, byte[] value) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.set (key, value);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static void set (Byte[] key, byte[] value, int time) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();            Jedis.set (key, value);        Jedis.expire (key, time);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis); E.pRintstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static void Hset (byte[] key, byte[] field, byte[] value) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.hset (Key, field, value);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static void Hset (String key, String field, String value) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.hset (Key, field, value);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis); }}/** * Get data * * @param key * @return */public static StringHget (String key, String field) {string value = null;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Value = Jedis.hget (key, field);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return value;        }/** * Get data * * @param key * @return */public static byte[] Hget (byte[] key, byte[] field) {        byte[] value = NULL;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Value = Jedis.hget (key, field);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return value; } public static void Hdel (byte[] key, byte[] field) {JedisJedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.hdel (key, field);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis); }}/** * Store Redis Queue Order Store * @param key Reids Key Name * @param value Key value */public static void Lpush (byt        E[] key, byte[] value) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.lpush (key, value);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis); }}/** * Storage Redis Queue Reverse storage * @param key Reids Key Name * @param value Key value */public static void Rpush (byt        E[] key, byte[] value) {Jedis Jedis = null; try {Jedis = JedispoOl.getresource ();        Jedis.rpush (key, value);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis); }}/** * pops the last element in the list source (the trailing element) and returns it to the client * @param key Reids Key name * @param destination Key value */PU        Blic static void Rpoplpush (byte[] key, byte[] destination) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.rpoplpush (key, destination);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis); }}/** * Get queue data * @param key Key Name * @return * */public static List lpoplist (byte[] key) {L        IST list = null;        Jedis Jedis = null; try {Jedis = Jedispool.getresource();        List = Jedis.lrange (key, 0,-1);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return list; /** * Get Queue data * @param key Key Name * @return * * public static byte[] Rpop (byte[] key) {byte[] b        Ytes = null;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        bytes = Jedis.rpop (key);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return bytes;        } public static void Hmset (Object key, Map hash) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.hmset (key.tostring (), hash); } catch (Exception e) {//release REDis Object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static void Hmset (Object key, Map hash, int time) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();            Jedis.hmset (key.tostring (), hash);        Jedis.expire (Key.tostring (), time);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static list Hmget (Object key, String ... fields) {list result = null;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        result = Jedis.hmget (key.tostring (), fields);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace (); } finally{//Return to Connection pool close (Jedis);    } return result;        public static set Hkeys (String key) {set result = NULL;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        result = Jedis.hkeys (key);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return result;        } public static list Lrange (byte[] key, int from, int to) {list result = null;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        result = Jedis.lrange (key, from, to);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return result; } public static Map Hgetall (byte[] Key) {MAP result = null;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        result = Jedis.hgetall (key);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return result;        } public static void Del (byte[] key) {Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.del (key);            } catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);        }} public static long Llen (byte[] key) {long len = 0;        Jedis Jedis = null;            try {Jedis = Jedispool.getresource ();        Jedis.llen (key); } catch (Exception e) {//Releases Redis object JEDispool.returnbrokenresource (Jedis);        E.printstacktrace ();        } finally {//return to Connection pool close (Jedis);    } return len; }}
Configuration information for Redis is mainly used to read
Package Utils;import java.io.ioexception;import Java.io.inputstream;import java.util.properties;/** * Created by KINGLF on 2016/10/17.    */public class Configuration extends Properties {private static final long serialversionuid = -2296275030489943706l;    private static Configuration instance = NULL; public static synchronized Configuration getinstance () {if (instance = = null) {instance = new Configur        Ation ();    } return instance;        } public string GetProperty (string key, String defaultvalue) {string val = GetProperty (key); return (val = = NULL | | val.isempty ())?    Defaultvalue:val;    public string getString (string name, String defaultvalue) {return This.getproperty (name, DefaultValue);        } public int GetInt (string name, int defaultvalue) {string val = This.getproperty (name); return (val = = NULL | | val.isempty ())?    DefaultValue:Integer.parseInt (Val); } public long Getlong (String name, longDefaultValue) {String val = this.getproperty (name); return (val = = NULL | | val.isempty ())?    DefaultValue:Integer.parseInt (Val);        } Public float GetFloat (string name, float defaultvalue) {string val = This.getproperty (name); return (val = = NULL | | val.isempty ())?    DefaultValue:Float.parseFloat (Val);        } public double GetDouble (string name, double defaultvalue) {string val = This.getproperty (name); return (val = = NULL | | val.isempty ())?    DefaultValue:Double.parseDouble (Val);        } public byte GetByte (string name, byte defaultvalue) {string val = This.getproperty (name); return (val = = NULL | | val.isempty ())?    DefaultValue:Byte.parseByte (Val); Public Configuration () {InputStream in = Classloader.getsystemclassloader (). getResourceAsStream ("config +")        ;            try {this.loadfromxml (in);        In.close (); } catch (IOException IoE) {}}}
V. Testing
Import Model.message;import utils.jedisutil;import Utils.objectutil;import Redis.clients.jedis.jedis;import java.io.ioexception;/** * Created by KINGLF on 2016/10/17.    */public class Testredisqueue {public static byte[] Rediskey = "key". GetBytes ();        static {try {init ();        } catch (IOException e) {e.printstacktrace ();  }} private static void Init () throws IOException {for (int i = 0; i < 1000000; i++) {Message            message = new Message (I, "This is the first" + i + "content");        Jedisutil.lpush (Rediskey, objectutil.object2bytes (message));        }} public static void Main (string[] args) {try {pop ();        } catch (Exception e) {e.printstacktrace ();        }} private static void Pop () throws Exception {byte[] bytes = Jedisutil.rpop (Rediskey);        Message msg = (message) objectutil.bytes2object (bytes); if (msg! = null) {System.out.println (Msg.getid () + "----" + msg.getcontent ()); }    }}
Each time the Pop () method is executed, the result is as follows:
<br>1----This is the 1th content
<BR>2----This is the 2nd content
<br>3----This is the 3rd content
<br>4----This is the 4th content

Summarize

至此,整个Redis消息队列的生产者和消费者代码已经完成

    1. Message需要传送的实体类(需实现Serializable接口)
    2. ConfigurationRedis的配置读取类,继承自Properties
    3. Objectutil将对象和byte数组双向转换的工具类
    4. Jedis通过消息队列的先进先出(FIFO)的特点结合Redis的list中的push和pop操作进行封装的工具类

Java implements Message Queuing with Redis

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.