Package Com.redis.learn.util;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import Redis.clients.jedis.jedispoolconfig;public class Redistool {//redis server address private static String address = "localhost";// Redis Server port number private static int port = 6379;//access password private static String auth = null;//The maximum number of available connection instances, the default value is 8;//if the assignment is-1, it means no limit If the pool is already assigned a maxactive Jedis instance, the pool's state is exhausted (exhausted) at this point. private static final int max_active = 1024;//controls the maximum number of Jedis instances in a pool that have a state of idle (idle), and the default value is 8. private static int max_idle = 10;//The maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out. If the wait time is exceeded, the direct throw jedisconnectionexception;private static int max_wait = 10000;private static int TIMEOUT = 10000;// Whether the validate operation is performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instance is available; private static Boolean test_on_borrow = True;private Static Jedispool jedispool;static {jedispoolconfig config = new Jedispoolconfig (); Config.setmaxidle (Max_idle); Config.setmaxwaitmillis (max_wait); Config.settestonborrow (Test_on_borrow);//config.setmaxtotal (MAX_ACTIVE); JedispoOL = new Jedispool (config, address, port, TIMEOUT);} /** * Get Jedis client * @return */public static Jedis Getjedis () {Jedis Jedis = null;if (null! = Jedispool) {Jedis = JEDISPOOL.G Etresource ();} return Jedis;} /** * Return resources * @param Jedis */public static void Returnresource (Jedis Jedis) {jedispool.returnbrokenresource (Jedis);}}
Package Com.redis.learn.util;import Java.nio.charset.charset;import Java.util.list;import java.util.Map;import Java.util.set;import redis.clients.jedis.jedis;/** * Redis related operations * @author XIANGLJ */public class Redisutil {private static Final Charset utf_8 = Charset.forname ("Utf-8"),/** * New string key value pair to Redis * @param key * @param value */public static Boolean s Etstring (string key, String value) {if (null = = Key | | value = = NULL) {return false;} Return SetBytes (Key.getbytes (Utf_8), Value.getbytes (Utf_8));} /** * byte array for storing key-value pairs in Redis, up to 1GB bytes * @param key * @param value value * @return */public static Boolean setbytes (byte[] K EY, byte[] value) {if (null = = Key | | null = = value) {return false;} Jedis Jedis = Redistool.getjedis (); String StatusCode = Jedis.set (key, value); System.out.println ("Status code: (" + StatusCode + ")"); Redistool.returnresource (Jedis); return true;} /** * Gets the value of String type * @param the value of the key key * @return */public static string getString (string key) {if (null = = key) {return null;} Byte[] val = getbyteS (key.getbytes (utf_8)); if (val = = null) {return null;} return new String (Val, utf_8);} /** * Get cached values in Redis * @param key * @return */public static byte[] GetBytes (byte[] key) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); byte[] val = jedis.get (key); Redistool.returnresource (Jedis); return Val;} /** * Delete a key, if the key is deleted, when the same key is requested again, returns Null * @param key */private static Boolean del (byte[] key) {if (null = = key) {return true;} Jedis Jedis = Redistool.getjedis (); Jedis.del (key); return true;} /** * Action String type (string), delete key * @param key * @return */public static Boolean delstring (String key) {if (null = = key) {return TR UE;} byte[] k = key.getbytes (utf_8); return del (k);} /** * BULK INSERT Cache:<br> * key,value,key,value<br> * For example <br> * name,johnny,age,12<br> * will add Name=johnny, The age=12 cache, which is updated immediately if the same cache already exists in the cache. * @param keyvalues * @return */public static Boolean Fetchset (String ... keyvalues) {if (keyvalues = = null) {return false;} Jedis Jedis = Redistool.getjedis (); Jedis.mset (KeyValues); RediStool.returnresource (Jedis); return true;} /** * Insert a simple type of map * @param key * @param map */public static void Addmap (String key, map<string, string> map) {if (Nu ll = = Key | | NULL = = map) {return;} Jedis Jedis = Redistool.getjedis (); Jedis.hmset (key, map); Redistool.returnresource (Jedis);} public static void Addmapval (String key, String field, String value) {if (null = = Key | | field = NULL | | null = = value) {R Eturn;} Jedis Jedis = Redistool.getjedis (); Jedis.hsetnx (Key, field, value); Redistool.returnresource (Jedis);} public static void Addmapval (byte[] key, byte[] field, byte[] value) {if (null = = Key | | field = NULL | | null = = value) {R Eturn;} Jedis Jedis = Redistool.getjedis (); Jedis.hsetnx (Key, field, value); Redistool.returnresource (Jedis);} /** * Insert a MAP value into Redis * @param key * @param mapbyte */public static void Addmap (byte[] key, map<byte[], byte[]> map Byte) {if (null = = Key | | null = = mapbyte) {return;} Jedis Jedis = Redistool.getjedis ()///always returns OK and does not execute failed string status = Jedis.hmset (kEY, mapbyte); System.out.println ("Execution Status:" + status); Redistool.returnresource (Jedis);} /** * Gets the value in map, only can * @param key * @return */public static list<string> getmapval (string key, String ... fields) {if ( NULL = = key) {return null;} Jedis Jedis = Redistool.getjedis (); list<string> rtnlist = null;if (Null = = Fields | | fields.length = = 0) {rtnlist = Jedis.hvals (key);} else {rtnlist = j Edis.hmget (key, fields);} Redistool.returnresource (Jedis); return rtnlist;} /** * Get the value in Map * @param key * @param fields * @return */public static list<byte[]> getmapval (byte[] key, byte[] ... Fields) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); if (!jedis.exists (key)) {return null;} list<byte[]> rtnlist = null;if (Null = = Fields | | fields.length = = 0) {rtnlist = Jedis.hvals (key);} else {rtnlist = j Edis.hmget (key, fields);} return rtnlist;} /** * Add set Set to Redis * @param key * @param values */public static void AddSet (String key, String ... values) {if (null = = K EY | | Values = = NULL) {return;} Jedis Jedis = Redistool.getjedis (); Jedis.sadd (key, values);} public static void Delsetval (String key, String ... fields) {if (null = = key) {return;} if (fields = = NULL | | fields.length = = 0) {del (key.getbytes (utf_8)); return;} Jedis Jedis = Redistool.getjedis (); Jedis.srem (key, fields); Redistool.returnresource (Jedis);} public static void Addsetbytes (byte[] key, byte[]...values) {if (null = = Key | | values = NULL) {return;} Jedis Jedis = Redistool.getjedis (); Jedis.sadd (key, values); Redistool.returnresource (Jedis);} public static void Delsetval (byte[] key, byte[]...values) {if (null = = key) {return;} if (values = = NULL | | values.length = = 0) {del (key); return;} Jedis Jedis = Redistool.getjedis (); Jedis.srem (key, values); Redistool.returnresource (Jedis);} /** * Get all values * @param key */public static set<byte[]> getsetvals (byte[] key) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); set<byte[]> rtnlist = jedis.smembers (key); return rtnlist;} public static set<string>Getsetvals (String key) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); set<string> Rtnset = jedis.smembers (key); Redistool.returnresource (Jedis); return rtnset;} /** * Determines whether the set set contains elements * @param key * @param field * @return */public static Boolean Issetcontain (String key, String field) {if (null = = Key | | field = NULL) {return false;} Jedis Jedis = Redistool.getjedis (); Boolean iscontain = Jedis.sismember (key, field); Redistool.returnresource (Jedis); return iscontain;} public static Boolean Issetcontain (byte[] key, byte[] field) {if (null = = Key | | field = = NULL) {return false;} Jedis Jedis = Redistool.getjedis (); Boolean issuccess = Jedis.sismember (key, field); Redistool.returnresource (Jedis); return issuccess;} /** * Returns the number of elements in the set set * @param key * @return */public static Long getsetlength (String key) {if (null = = key) {return 0L;} Jedis Jedis = Redistool.getjedis (); Long length = Jedis.scard (key); return length;} public static Long Getsetlength (byte[] key) {if (null = = key) {return 0L;} Jedis Jedis = Redistool.getjedis (); Long length = Jedis.scard (key); Redistool.returnresource (Jedis); return length;} /** * add element to list collection * @param key * @param values */public static void Addlist (String key, String ... values) {if (Null = = key || values = = null) {return;} Jedis Jedis = Redistool.getjedis (); Jedis.rpush (key, values); Redistool.returnresource (Jedis);} /** * add element to list collection * @param key * @param values */public static void Addlist (byte[] key, byte[] ... values) {if (Null = = key || values = = null) {return;} Jedis Jedis = Redistool.getjedis (); Jedis.rpush (key, values); Redistool.returnresource (Jedis);} /** * Gets the value of start to end range beyond the range of List, does not throw an exception * @param key * @param start * @param end * @return */public static LIST<STRING&G T Getlistvals (String key, int start, int end) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); list<string> rtnlist = Jedis.lrange (key, start, end); Redistool.returnresource (Jedis); return rtnlist;} /** * Gets the value of start to end range beyond the range of list, does not throw an exception * @param key * @Param start * @param end * @return */public static list<byte[]> getlistvals (byte[] key, int start, int end) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); list<byte[]> rtnlist = Jedis.lrange (key, start, end); Redistool.returnresource (Jedis); return rtnlist;} public static list<string> Getlistall (String key) {if (null = = key) {return null;} Return getlistvals (key, 0,-1);} public static list<byte[]> Getlistall (byte[] key) {if (null = = key) {return null;} Return getlistvals (key, 0,-1);} public static string Poplist (string key) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); return Jedis.lpop (key);} public static byte[] Poplist (byte[] key) {if (null = = key) {return null;} Jedis Jedis = Redistool.getjedis (); return Jedis.lpop (key);}}
Package Com.redis.learn.client;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 Java.nio.charset.charset;import Java.util.arrays;import Java.util.HashMap;import Java.util.list;import Java.util.map;import Org.junit.test;import Com.redis.learn.util.redisutil;public class Redisutiltest {private static final Charset Utf_8 = Charset.forname ("Utf-8"); @Testpublic void TestString () { System.err.println ("Test string type start >>\r\n\t"); String key = "program Name"; String value = "Redis for Windows"; String value1 = "Input Redis for bytes"; Redisutil.setstring (key, value); Redisutil.setbytes (Key.getbytes (Utf_8), Value1.getbytes (Utf_8)); System.out.println ("Get name:>>>\r\n\t from Redis"); String val = redisutil.getstring (key); System.out.println ("Output: \r\n\t" + val); System.out.println ("Get name bytes:>>>>\r\n\t from Redis"); byte[] bytes = Redisutil.GetBytes (Key.getbytes (utf_8)); System.out.println ("Output bytes:\r\n\t" + arrays.tostring (bytes)); val = new String (bytes, utf_8); System.out.println ("converted String:\r\n\t" + val); System.out.println ("Delete key of name: \r\n\t"); Redisutil.delstring (key); val = redisutil.getstring (key); System.out.println ("Get Again:" + (val==null? ") The key has been deleted ... ": Val));} @Testpublic void TestMap () {System.err.println ("Test Redis for Map start:>>>>");//Simple String mapmap<string, string> Strmap = new hashmap<string, string> ();//complex point mapmap<byte[], byte[]> bytesmap = new HashMap< Byte[], byte[]> ();//test stores the new address Strmap.put ("OS", "Windows"), Strmap.put ("Language", "ch"), Strmap.put ("Tool", " Redis for Windows "); string skey = "string for Redis"; Redisutil.addmap (Skey, strmap);//from getting all the values list<string> sList = Redisutil.getmapval (skey); SYSTEM.OUT.PRINTLN ("All result values:" + sList);//Give values in field order given sList = Redisutil.getmapval (Skey, "Tool", "OS", "Language", "DD") )///Find out the values and enter the field in the same order System.out.println ("Output value [Tool, OS, Language, DD]:\r\n\t "+ sList);//try to store the object in Redis person man = new Person (" Johnny ", 23," male ");//Serialized object Bytearrayoutputstream BAOs = new Byte Arrayoutputstream (); ObjectOutputStream Oos = Null;objectinputstream bis = null;try {oos = new ObjectOutputStream (BAOs); /Create Object Oos.writeobject (person);//Gets the bytecode after serialization byte[] bytes = Baos.tobytearray (); Bytesmap.put (Person.getname (). GetBytes (utf_8), bytes); Redisutil.addmap (Person.getname (). GetBytes (Utf_8), bytesmap);//Read objects from Redis list<byte[]> list= Redisutil.getmapval (Person.getname (). GetBytes (Utf_8), Person.getname (). GetBytes (Utf_8)); if (list.size () = = 1) { bytes = list.get (0); Bytearrayinputstream Bais = new Bytearrayinputstream (bytes); bis = new ObjectInputStream (Bais); Person P = (person) bis.readobject (); System.out.println ("Get to object:" + P); bais.close (); Bis.close ();}} catch (Exception e) {e.printstacktrace ();} finally {try {if (BAOs! = null) {Baos.close ();} if (null! = Oos) {oos.close ();}} catch (IOException e) {e.printstacktrace ();}} Adds a new key value pair to the existing key Redisutil.addmapval (PersoN.getname (). GetBytes (Utf_8), "Addtest". GetBytes (Utf_8), "Test Redis Adding A Val for Exist Key". GetBytes (Utf_8));// Gets the value just inserted System.out.println ("Get the value just inserted: \r\n\t" + New String (Redisutil.getmapval (Person.getname (). GetBytes (Utf_8), " Addtest ". GetBytes (Utf_8)). Get (0)));//try to interpolate redisutil.addmapval to a nonexistent key (" Addnewkey "," Addnewmapkey "," Addnewmapval "), or//To obtain a value, it also indicates that the key value pair of the object is automatically created to save when the interpolation of the key does not exist. System.out.println ("Try to get the value just inserted: \r\n\t" + redisutil.getmapval ("Addnewkey", "Addnewmapkey"));} @Testpublic void Testset () {System.err.println ("Test Redis for Set start:>>>>>>>");// add Element Redisutil.addset ("Addnewset", "Set1", "Set2", "Set3") to Redis,//Get the value in set SYSTEM.OUT.PRINTLN ("Length of Set Set: \r\n\t" + Redisutil.getsetlength ("Addnewset")); System.out.println ("Set set element: \r\n\t" + redisutil.getsetvals ("Addnewset"));//attempt to remove element Redisutil.delsetval ("Addnewset" , "Set2"); System.out.println ("Length of Set Set: \r\n\t" + redisutil.getsetlength ("Addnewset")); System.out.println ("Set set element: \r\n\t" + redisutil.getsetvals ("Addnewset"));//JudgmentWhether to include the element System.out.println ("contains the value of Set2:" + redisutil.issetcontain ("Addnewset", "Set2")); System.out.println ("contains the value of Set2:" + redisutil.issetcontain ("Addnewset", "Set3"));} @Testpublic void Testlist () {System.err.println ("Test Redis for List start:>>>>>>");// Add the Element redisutil.addlist ("Vallist", "List1", "List2", "List3") to the list and/or get the value in the list System.out.println ("The value in the Redis for list is : "+ redisutil.getlistall (" vallist "));//Popup The first element of the list System.out.println (" Popup first element: "+ redisutil.poplist (" vallist "); System.out.println (the value in the Redis for list is: "+ redisutil.getlistall (" vallist "));}} Class Person implements Serializable {private static final long Serialversionuid = 8737363017319228700l;private String nam e;private int age;private string sex;public person (string name, Int. age, String sex) {this.name = Name;this.age = Age;this . sex = sex;} 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;} PublIC String getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} @Overridepublic String toString () {return "person [name=" + name + ", age=" + Age + ", sex=" + Sex + "]";}}
These are the package and test classes that do some of the basic operations of Redis, for reference only
The use of Redis by Java