Application Scenarios
Recently in the company to do projects, need to store chat content, taking into account the database query the number of IO connections high, connected frequently factors, decided to use the cache.
Knowing from the web that Redis can store all the content in binary, and that Java is able to serialize all the objects, the serialized method provides the implementation in the following code.
Serialization of
Here I have written a Java serialization tool, mainly converting objects to byte[], and deserializing them into Java objects based on the byte[] array;
The main use of Bytearrayoutputstream and bytearrayinputstream;
It is important to note that each custom need to serialize the object to implement the Serializable interface;
The code is as follows:
Package Com.bean.util;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;public class ObjectUtil {/** Object Goto byte[] * @param obj * @return * @throws ioexception */public static byte[] Objecttobytes (Object obj) throws Exception{b Ytearrayoutputstream bo = new Bytearrayoutputstream (); ObjectOutputStream oo = new ObjectOutputStream (bo); O O.writeobject (obj); byte[] bytes = Bo.tobytearray (); Bo.close (); Oo.close (); return bytes;} /**byte[] Turn to Object * @param bytes * @return * @throws Exception */public static Object Bytestoobject (byte[] bytes) throws Except Ion{bytearrayinputstream in = new Bytearrayinputstream (bytes), ObjectInputStream sIn = new ObjectInputStream (in), return Sin.readobject ();}}
Defines a message class that is used primarily to receive message content and the settings for the following table of messages.
Package Com.bean;import java.io.serializable;/** defines the message class to receive message content and set the subscript for the message * @author Lenovo * */public class message implements Serializable{private static final Long serialversionuid = 7792729l;private int id;private String 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;}}
Using Redis as a queue, we use the push and pop operations of the list in Redis;
Characteristics of the combined queue:
- Allow only one end to be inserted
- The new element can only be at the end of the queue
- FIFO: Advanced First Out principle
Lpush (Rpop) or Rpush (Lpop) in Redis can meet the requirements, while the objects in the list for push or pop in Redis need only be converted to byte[].
Java uses Jedis for Redis storage and Redis connection pooling settings
Package Com.redis.util;import Java.util.list;import Java.util.map;import java.util.set;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import Redis.clients.jedis.jedispoolconfig;public Class Jedisutil {private static string jedis_ip;private static int jedis_port;private static string Jedis_password;//priv Ate static String jedis_slave;private static Jedispool jedispool;static {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); Config.setmaxidle (256);// 20config.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 = null; Jedis Jedis = null;try {Jedis = Jedispool.getresource (); value = Jedis.get (key);} catch (Exception e) {//Release Redis object Jedispool . Returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return value;} public static void Close (Jedis Jedis) {try {jedispool.returnresource (Jedis);} catch (Exception e) {if (jedis.isconnected ( ) {jedis.quit (); Jedis.disconnect ();}}} /** * Get Data * * @param key * @return */public static byte[] Get (byte[] key) {byte[] value = NULL; Jedis Jedis = null;try {Jedis = Jedispool.getresource (); value = Jedis.get (key);} catch (Exception e) {//Release 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, V Alue);} 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 (); j Edis.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 (); j Edis.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 string Hget (String key, String field) {String value = Null Jedis Jedis = null;try {Jedis = Jedispool.getresource (); value = Jedis.hget (key, field);} catch (Exception e) {//Release Redis object J Edispool.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) {//Release Redis object J Edispool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return value;} public static void Hdel (byte[] key, byte[] field) {Jedis Jedis = 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);}} /** * Storage Redis Queue Order storage * @param byte[] key Reids Key name * @param byte[] Value key value */public static void Lpush (byte[] key, byte[] VA Lue) {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 byte[] key Reids Key name * @param byte[] Value key value */public static void Rpush (byte[] key, byte[] VA Lue) {Jedis Jedis = null;try {Jedis = Jedispool.getresource (); Jedis.rpush (key, value);} catch (Exception e) {//Release Redis Object JE Dispool.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 byte[] key Reids Key name * @param byte[] Value key value */public static void Rpoplpu SH (byte[] key, byte[] destination) {Jedis Jedis = null;try {Jedis = Jedispool.getresource (); Jedis.rpoplpush (Key, Destinat ION);} catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close ( Jedis);}} /** * Get Queue data * @param byte[] Key name * @return */public static list<byte[]> lpoplist (byte[] key) {list<byte[]> list = null; JEdis Jedis = null;try {Jedis = Jedispool.getresource (); list = Jedis.lrange (key, 0,-1);} catch (Exception e) {//Release Redis object J Edispool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return list;} /** * Get Queue data * @param byte[] key key name * @return */public static byte[] Rpop (byte[] key) {byte[] bytes = NULL; Jedis Jedis = null;try {Jedis = Jedispool.getresource (); bytes = Jedis.rpop (key);} catch (Exception e) {//Release Redis object Jedispoo L.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return bytes;} public static void Hmset (Object key, map<string, string> hash) {Jedis Jedis = null;try {Jedis = Jedispool.getresourc E (); Jedis.hmset (key.tostring (), hash);} catch (Exception e) {//Releases Redis object Jedispool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close ( Jedis);}} public static void Hmset (Object key, map<string, string> 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<string> Hmget (Object key, String ... fields) {list<string> 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<string> Hkeys (String key) {set<string> result = null; Jedis Jedis = null;try {Jedis = Jedispool.getresource (); result = Jedis.hkeys (key);} catch (Exception e) {//Release Redis object Jedisp Ool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return result;} public static list<byte[]> Lrange (byte[] key, int. from, int. to) {list<byte[]> 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<byte[], byte[]> hgetall (byte[] key) {map<byte[], byte[]> result = null; Jedis Jedis = null;try {Jedis = Jedispool.getresource (); result = Jedis.hgetall (key);} catch (Exception e) {//Release Redis object Jedi Spool.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 (Except Ion e) {//Release 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 the Redis object Jedispool.returnbrokenresource (Jedis); E.printstacktrace ();} finally {//return to Connection pool close (Jedis);} return len;}}
Configuration is primarily used to read Redis configuration information
Package Com.redis.util;import Java.io.ioexception;import Java.io.inputstream;import java.util.properties;public Class Configuration extends Properties {private static final long Serialversionuid = 50440463580273222l;private static Con figuration instance = null;public static synchronized Configuration getinstance () {if (instance = = null) {instance = new C Onfiguration ();} return instance;} public string GetProperty (string key, String defaultvalue) {string val = GetProperty (key); return (val = = NULL | | val.isemp Ty ())? 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, long defaultvalue) {string val = This.getproperty (name); return (val = = NULL | | val.isempt Y ())? DefaultValue:Integer.parseInt (val);} Public float getfloat (string name, float defaultvalue) {String val = this.getproperty (name); return (val = = NULL | | val.isempty ())? defaultvalue:f Loat.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.isempt Y ())? DefaultValue:Byte.parseByte (val);} Public Configuration () {InputStream in = Classloader.getsystemclassloader (). getResourceAsStream ("config"); try { This.loadfromxml (in); In.close ();} catch (IOException e) {}}}
Test Redis Queue
Package Com.quene.test;import Com.bean.message;import Com.bean.util.objectutil;import com.redis.util.JedisUtil; public class Testredisquene {public static byte[] Rediskey = "key". GetBytes (); Static{init ();} public static void Main (string[] args) {pop ();} private static void Pop () {byte[] bytes = Jedisutil.rpop (Rediskey); Message msg = (message) objectutil.bytestoobject (bytes), if (msg! = null) {System.out.println (Msg.getid () + " " + Msg.getcontent ());}} private static void Init () {Message MSG1 = new Message (1, "Content 1"); Jedisutil.lpush (Rediskey, Objectutil.objecttobytes (MSG1)); Message MSG2 = new Message (2, "Content 2"); Jedisutil.lpush (Rediskey, Objectutil.objecttobytes (MSG2)); Message MSG3 = new Message (3, "Content 3"); Jedisutil.lpush (Rediskey, Objectutil.objecttobytes (MSG3));}} The test results are as follows:
1 content 1
2 Content 2
3 Content 3
Use of Jedis to implement Redis Message Queuing using Java Redis