Java Operating Redis DB instance (Redis cluster)

Source: Internet
Author: User
Tags crc32 gettext tojson redis cluster redis server

1. Configuring Redis Cluster
<?xml version= "1.0" encoding= "UTF-8"?><rediscluster><!--userroute--><clustergroup name= " Userroute "selectdb=" 1 "><server host=" 10.177.129.16 "port=" 6379 "></server><server host=" 10.177.129.15 "port=" 6379 "></server></clusterGroup><!--sessionroute--><clustergroup Name = "Sessionroute" selectdb= "2" ><server host= "10.177.129.16" port= "6379" ></server><server host= " 10.177.129.15 "port=" 6379 "></server></clusterGroup><!--publicdata--><clustergroup name=" Publicdata "><server host=" 10.177.129.16 "port=" 6379 "></server><server host=" 10.177.129.15 "port= "6379" ></server></clusterGroup></redisCluster>

2. Create a Redis connection attribute entity class
Package com.isoftstone.cms.syscore.pojo;/** * Redis Connection Properties * @author Xiakai * */public class Rediscluster {private String sel Ectdb;private string Hostip;private stringport;public string Getselectdb () {return selectdb;} public void Setselectdb (String selectdb) {this.selectdb = Selectdb;} Public String Gethostip () {return hostip;} public void Sethostip (String hostip) {this.hostip = HostIP;} Public String Getport () {return port;} public void Setport (String port) {this.port = port;}}

3. Analyzing redis cluster configuration
Package Com.iss.itreasury.test.jedis;import Java.io.ioexception;import Java.util.arraylist;import Java.util.hashmap;import java.util.iterator;import java.util.list;import Java.util.map;import java.util.Set;import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.element;import Org.dom4j.io.SAXReader; Import Org.springframework.core.io.ClassPathResource; Import Org.springframework.core.io.Resource; import org.springframework.core.io.support.encodedresource;/** * resolves redis cluster configuration * @author Xiakai * */public class redisconfig {public static map<string,list<rediscluster>> Redisgroupmap = null;//parameter Constructor public redisconfig () {}//gets all Clustergroup group key values to public static map<string,list<rediscluster>> Getredisgroupmap () {// Read XML file document Document=readxmlfile ();//Get Clustergroup node key and listif (Redisgroupmap = = null) {redisgroupmap= Getmapbyitemsgroup (document);} return redisgroupmap;} Read Redisconfig configuration file private static document Readxmlfile () {//Create read-in Object Saxreader reaDer = new Saxreader ();    Create document instance document Doc=null;     try {//load file from Classpath redisconfig.xml Resource Resource = new Classpathresource ("Redisclusterconfig.xml"); Specifies the encoding format (UTF-8) corresponding to the file resource in order to correctly read the contents of the file without garbled encodedresource Encoderesource = new Encodedresource (Resource, "UTF-8")     ;     doc = Reader.read (Encoderesource.getreader ());} catch (IOException e) {System.out.println ("Unable to read system configuration file Redisconfig.xml, possibly the file does not exist"),} catch (Documentexception e) {System . OUT.PRINTLN ("An exception occurred in parsing the redisconfig.xml file");} return doc;} Reads the XML node and returns the Mapprivate static map<string,list<rediscluster>> Getmapbyitemsgroup of the node Redisgroup ( Document document) {map<string,list<rediscluster>> Itemmap=new Hashmap<string,list<rediscluster >> (); try{//gets the root node element root=document.getrootelement ();//gets listlist itemslist= for all child nodes under the root node Clustergroup Root.selectnodes ("./clustergroup"); for (int i=0;i<itemslist.size (); i++) {//Get node itemselement items= (Element) Itemslist.get (i); String Groupname=items. Attribute ("name"). GetText (); String Selectdb = Items.attribute ("Selectdb") ==null? "": Items.attribute ("Selectdb"). GetText ();//if (groupname!=null &&groupname.equals (This.getgroupname ())) {//Get a list of all child node service Clustergroup under the Itemlist=items.elements ();  Get the value of the service node list<rediscluster> redisclusterlist = GetItemList (ITEMLIST,SELECTDB); Itemmap.put (GroupName, redisclusterlist);//}}}catch (Exception e) {}return itemmap;} Get the Redis service node for all item under node private static list<rediscluster> GetItemList (List itemlist,string selectdb) {list< rediscluster> redisclusterlist = new arraylist<rediscluster> (); for (int i=0;i<itemlist.size (); i++) {// Get node Serverelement item= (Element) itemlist.get (i); String HostIP = Item.attribute ("host"). GetText (); String port = item.attribute ("port"). GetText (); Rediscluster rediscluster =new rediscluster (); Rediscluster.sethostip (HostIP); Rediscluster.setport (port);   Rediscluster.setselectdb (SELECTDB); Redisclusterlist.add (Rediscluster); }return RediscLusterlist;} public static void Main (string[] args) {getredisgroupmap ();//jedisutil.insertpublicdataobject ("User1", "Zhang San", Jedisutil.online_user);//jedisutil.insertpublicdataobject ("User2", "John Doe", jedisutil.online_user);//  Jedisutil.insertpublicdataobject ("User3", "Harry", Jedisutil.online_user);  Set s = jedisutil.getallset (Jedisutil.online_user);   Iterator it = S.iterator ();   while (It.hasnext ()) {string key = (string) it.next ();   String value = jedisutil.getstring (Key,jedisutil.online_user);  SYSTEM.OUT.PRINTLN (key + value); }string test = jedisutil.getstring ("user1", Jedisutil.online_user); SYSTEM.OUT.PRINTLN (test);}}


4. Tools to operate the Redis database
Package Com.isoftstone.cms.syscore.utils;import Java.lang.reflect.type;import Java.util.list;import java.util.Set; Import Java.util.zip.crc32;import Redis.clients.jedis.jedis;import Redis.clients.jedis.exceptions.jedisconnectionexception;import Com.google.gson.gson;import Com.isoftstone.cms.syscore.pojo.rediscluster;public class Jedisutil {//Database public static final String Store_loginuser = "4";//Merchant login user public static final string store_info = "5";//Merchant status Merchant Purchase service validity period public static final String Check_code = "6";//Test Code public static final String menu = "7";//all menu public static final String service = "8";//service Charge Information public static final Strin G Store_loginkey = "9";//Initialize login public key to//fixed keypublic static final String All_menu_key = "All_menu_key";p ublic static final String buy_service_key = "Buy_service_key";//service charge purchase keypublic static final String All_service_key = "All_service_key";// All services public static final String menu_authority = "menu_authority";//Menu Permissions public static final String store_menu_key = "STORE_menu_key ";//Require Merchant assigned business menu public static final String Store_service_key =" Store_service_key ";//merchant charges keypublic static Final string syste_menu_key = "Syste_menu_key";//System Management menu key//Jedis Service Group Business type public static final string cont_clustername_ Publicdata = "Publicdata";p ublic static final String Cont_clustername_sessionroute = "Sessionroute";p ublic static final S Tring Cont_clustername_userroute = "Userroute";//operation mode 0 Insert 1 Get 2 Remove public static final long insert_operation = 0;public s Tatic final Long get_operation = 1;public static final Long delete_operation = 2;//Verification code expires in seconds public static final int CHECKCO  De_expireseconds = 5*60;//session expires seconds public static final int expireseconds = $ * 60;private static void Closejedis (Jedis Jedis) {try {jedis.quit ();} catch (Jedisconnectionexception e) {e.printstacktrace ();} Jedis.disconnect ();} /** * Get string based on key * * @param key * @param jedisgroup */public static string getString (string key, String selectdb) {Jedis J Edis = Getpublicdatajedis (key, Get_operation, SelecTDB); return Jedis.get (key);} /** * Get all data set * @param selectdb * @return */public static set Getallset (String selectdb) {Jedis Jedis = Getdatajedis (get _operation, Selectdb); return Jedis.keys ("*");} /** * Default fetching of the first database of the configuration file * @param operation * @param selectdb * @return */private static Jedis Getdatajedis (long operation, St Ring Selectdb) {if (Redisconfig.redisgroupmap = = null) {Redisconfig.redisgroupmap = Redisconfig.getredisgroupmap ();} list<rediscluster> clusterslist = RedisConfig.redisGroupMap.get (cont_clustername_publicdata); int clusterno = 0 ;//default to the first rediscluster cluster = Clusterslist.get (Clusterno); Jedis Jedis = new Jedis (Cluster.gethostip (), Integer.valueof (Cluster.getport ())), Jedis.select (Integer.valueof ( SELECTDB)); return Jedis;} /** * Delete Data * * @param key * @param jedisgroup */public static void DeleteObject (string key, String jedisgroup) {Jedis jedi s = Getjedis (key, Jedisgroup, delete_operation); Jedis.del (key); Closejedis (Jedis);} /** * Delete public data * * @param key * @param objclass * @pAram Selectdb */public static void Deletepublicdataobject (string key, String selectdb) {Jedis Jedis = Getpublicdatajedis (k EY, delete_operation, Selectdb); Jedis.del (key); Closejedis (Jedis);} /** * Get Jedis Library instance * * @param key * @param jedisgroup * @param operation * @return */private static Jedis Getjedis (String k EY, String Jedisgroup, long operation) {if (Redisconfig.redisgroupmap = = null) {Redisconfig.redisgroupmap = REDISCONFIG.G Etredisgroupmap ();} list<rediscluster> clusterslist = RedisConfig.redisGroupMap.get (jedisgroup); int arraylength = Clusterslist.size ();//The information should be credited to the int clusterno = Getredisno (key, Arraylength) based on the key value; Rediscluster cluster = Clusterslist.get (Clusterno); Jedis Jedis = new Jedis (Cluster.gethostip (), Integer.valueof (Cluster.getport ())), Jedis.select (Integer.valueof ( Cluster.getselectdb ())); return Jedis;} /** * Redis Key Value gets Object * * @param key * @param objclass * @param jedisgroup * @return */public static object GetObject (Strin G Key, Class objclass, String jedisgroup) {Jedis Jedis = Getjedis (key, Jedisgroup, get_operation); String sobj = Jedis.get (key); Closejedis (Jedis); Gson Gson = new Gson (); return Gson.fromjson (Sobj, objclass);} /** * Get library instances of public data Jedis * * @param key * @param jedisgroup * @param operation * @return */private static Jedis getpublicdata Jedis (string key, long operation, string selectdb) {if (Redisconfig.redisgroupmap = = null) {Redisconfig.redisgroupmap = Re Disconfig.getredisgroupmap ();} list<rediscluster> clusterslist = RedisConfig.redisGroupMap.get (cont_clustername_publicdata); int arraylength = Clusterslist.size ();//The information should be credited to the int clusterno = Getredisno (key, Arraylength) based on the key value; Rediscluster cluster = Clusterslist.get (Clusterno); Jedis Jedis = new Jedis (Cluster.gethostip (), Integer.valueof (Cluster.getport ())), Jedis.select (Integer.valueof ( SELECTDB)); return Jedis;} /** * Publicdata Redis Key Value Gets Object * * @param key * @param objclass * @param jedisgroup * @return */public static Object Getp Ublicdataobject (String key, Class objclass, string sELECTDB) {Jedis Jedis = Getpublicdatajedis (key, Get_operation, SELECTDB); String sobj = Jedis.get (key); Closejedis (Jedis); Gson Gson = new Gson (); return Gson.fromjson (Sobj, objclass);}  /** * Publicdata Redis key value gets Object list<entity> * * @param key * @param objclass * @param jedisgroup * @return */public Static Object Getpublicdataobjectbytype (string key, type type, string selectdb) {Jedis Jedis = Getpublicdatajedis (Key, GE T_operation, SELECTDB); String sobj = Jedis.get (key); Closejedis (Jedis); Gson Gson = new Gson (); return Gson.fromjson (Sobj, type);}  /** * Get Redis Server Library number * * @param hashkey * @return */public static int Getredisno (String key, int arraySize) {Long HashKey = Hash (key), int redisno = (int) (hashkey% arraySize); return Redisno;} /** * Calculates the hash value based on the key value * * @param k * @return */public static long hash (String k) {CRC32 CRC32 = new CRC32 (); Crc32.update (K.G Etbytes ()); return Crc32.getvalue ();} /** * Redis inserts an object into a different library based on the key value * * @param key * @param insertobj * @param jedisgroup */public static void InsertObject (String key, Object insertobj, String jedisgroup) {Jedis Jedis = Getjedis (key, Jedisgroup, Insert_operat ION); Gson Gson = new Gson () Jedis.set (Key, Gson.tojson (Insertobj)); Closejedis (Jedis);} /** * Redis inserts objects into different libraries based on key values * * @param key * @param insertobj * @param jedisgroup * @param expire */public static void I Nsertobject (String key, Object insertobj, string jedisgroup, int expireseconds) {Jedis Jedis = Getjedis (key, Jedisgroup, I Nsert_operation); Gson Gson = new Gson () Jedis.setex (Key, Expireseconds, Gson.tojson (insertobj)); Closejedis (Jedis);} /** * Publicdata Redis Inserts an object into a different library based on the key value * * @param key * @param insertobj * @param jedisgroup */public static void Insert Publicdataobject (String key, Object insertobj, String selectdb) {Jedis Jedis = Getpublicdatajedis (key, Insert_operation, SELECTDB); Gson Gson = new Gson () Jedis.set (Key, Gson.tojson (Insertobj)); Closejedis (Jedis);} /** * Publicdata Redis Inserts an object into a different library based on the key value, * * @param key * @param insertobj * @param jedisgroup * @param expireseconds */public static void Insertpublicdataobject (String key, Object insertobj, string selectdb, int ExpireS Econds) {Jedis Jedis = Getpublicdatajedis (key, Insert_operation, SELECTDB); Gson Gson = new Gson () Jedis.setex (Key, Expireseconds, Gson.tojson (insertobj)); Closejedis (Jedis);} /** * Update the timeout period for key in Redis * * @param key * @param jedisgroup * @param expireseconds */public static void Resetexpireseconds (S Tring Key, String jedisgroup, int expireseconds) {Jedis Jedis = Getjedis (key, Jedisgroup, get_operation); Jedis.expire (key , expireseconds); Closejedis (Jedis);}}


5, the required jar package

Java Operating Redis DB instance (Redis cluster)

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.