Application of Redis cluster version in Java, redis cluster version in java

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

Application of Redis cluster version in Java, redis cluster version in java

1. Configure the 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 property entity class

Package net. itxm. cms. syscore. pojo;/*** redis connection attribute **/public class RedisCluster {private String selectdb; private String hostIp; private String port; 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. parse redis cluster configuration

Package net. itxm. 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. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; import org. springframework. core. io. classPathResource; import org. s Pringframework. core. io. resource; import org. springframework. core. io. support. encodedResource;/*** resolve redis cluster configuration **/public class RedisConfig {public static Map <String, List <RedisCluster> redisGroupMap = null; // The constructor public RedisConfig () {}// obtain the public static Map key-value pairs of all tertergroup groups <String, List <RedisCluster> getRedisGroupMap () {// read the xml file Document document = readXmlFile (); // obtain the key and List if (redisGroupMap = null) {redisGroupMap = getMapByItemsGroup (document);} return redisGroupMap;} // read the redisConfig configuration file private static Document readXmlFile () {// create the read object SAXReader reader = new SAXReader (); // create the document instance Document doc = null; try {// load the file redisConfig from the class path. xml Resource resource = new ClassPathResource ("redisClusterConfig. xml "); // specifies the encoding format (UTF-8) corresponding to the file resource so that the file content can be correctly read without garbled EncodedReso Urce encodeResource = new EncodedResource (resource, "UTF-8"); doc = reader. read (encodeResource. getReader ();} catch (IOException e) {System. out. println ("the system configuration file redisConfig cannot be read. xml, the file may not exist ");} catch (incluentexception e) {System. out. println ("parse redisConfig. xml file exception ");} return doc;} // read the xml node and return the Map private static Map <String, List <RedisCluster> getMapByItemsGroup (Document document) of the redisGroup node) {Map <String, List <RedisCluster> itemmap = new HashMap <String, List <RedisCluster> (); try {// obtain the root node Element root = document. getRootElement (); // obtain the list List itemsList = root of all sub-nodes under the root node clusterGroup. selectNodes (". /clusterGroup "); for (int I = 0; I <itemsList. size (); I ++) {// get the node Items Element items = (Element) itemsList. get (I); String groupName = items. attribute ("name "). getText (); String selectdb = items. attribute ("selec Tdb ") = null? "": Items. attribute ("selectdb"). getText (); // if (groupName! = Null & groupName. equals (this. getGroupName () {// obtain the list List itemList = items of all sub-node services under clusterGroup. elements (); // obtain the service node Value List <RedisCluster> redisClusterList = getItemList (itemList, selectdb); itemmap. put (groupName, redisClusterList); // }}catch (Exception e) {} return itemmap ;} // obtain the apsaradb for redis service node private static List <RedisCluster> getItemList (List itemList, String selectdb) {List <RedisCluster> redisClusterList = new ArrayList <RedisCluster> (); for (int I = 0; I <itemList. size (); I ++) {// obtain the node server Element 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", "zhangsan", JedisUtil. ONLINE_USER); // JedisUtil. insertPublicDataObject ("user2", "Li Si", JedisUtil. ONLINE_USER); // JedisUtil. insertPublicDataObject ("user3", "Wang Wu", 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 used to operate redis Databases

Package net. itxm. 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 the validity period of the service purchased by the merchant is public static final String CHECK_CODE = "6"; // verification code: public static final String MENU = "7 "; // All menu public static final String SERVICE = "8"; // SERVICE billing information public static final String STORE_LOGINKEY = "9 "; // initialize the private key pair of the logon public key // fixed key public static final String ALL_MENU_KEY = "ALL_MENU_KEY"; public static final String BUY_SERVICE_KEY = "BUY_SERVICE_KEY "; // service charge purchase key public static final String ALL_SERVICE_KEY = "ALL_SERVICE_KEY"; // all services public static final String MENU_AUTHORITY = "MENU_AUTHORITY "; // menu permission public static final String STORE_MENU_KEY = "STORE_MENU_KEY"; // business menu to be allocated by the merchant public static final String STORE_SERVICE_KEY = "STORE_SERVICE_KEY "; // merchant's billing key public 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 "; public static final String CONT_CLUSTERNAME_SESSIONROUTE = "sessionRoute"; public static final String CONT_CLUSTERNAME_USERROUTE = "userRoute"; // operation method 0 insert 1 get 2 delete public static final long INSERT_OPERATION = 0; public static final long GET_OPERATION = 1; public static final long DELETE_OPERATION = 2; // verification code expiration seconds public static final int CHECKCODE_EXPIRESECONDS = 5*60; // session expiration seconds public static final int EXPIRESECONDS = 30*60; private static void closeJedis (Jedis jedis) {try {jedis. quit ();} catch (JedisConnectionException e) {e. printStackTrace ();} jedis. disconnect ();}/*** obtain the String based on the Key ** @ param key * @ param jedisGroup */public static String getString (String key, String selectdb) {Jedis jedis = 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 ("*");} /*** the first database in the configuration file is used by default * @ param operation * @ param selectdb * @ return */private static Jedis getDataJedis (long operation, String selectdb) {if (RedisConfig. redisGroupMap = null) {RedisConfig. redisGroupMap = RedisConfig. getRedisGroupMap ();} List <RedisCluster> clustersList = RedisConfig. redisGroupMap. get (CONT_CLUSTERNAME_PUBLICDATA); int clusterNo = 0; // The first RedisCluster cluster = clustersList is saved by default. 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 jedis = 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 (key, DELETE_OPERATION, selectdb); jedis. del (key); closeJedis (jedis );} /*** obtain the jedis database instance ** @ param key * @ param jedisGroup * @ param operation * @ return */private static Jedis getJedis (String key, String jedisGroup, long operation) {if (RedisConfig. redisGroupMap = null) {RedisConfig. redisGroupMap = RedisConfig. getRedisGroupMap ();} List <RedisCluster> clustersList = RedisConfig. redisGroupMap. get (jedisGroup); int arrayLength = clustersList. size (); // calculate the int clusterNo = getRedisNo (key, arrayLength) according to 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 ;} /*** obtain the redis key value Object ** @ param key * @ param objClass * @ param jedisGroup * @ return */public static Object getObject (String 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 );} /*** database instance for obtaining public data jedis ** @ param key * @ param jedisGroup * @ param operation * @ return */private static Jedis getPublicDataJedis (String key, long operation, string selectdb) {if (RedisConfig. redisGroupMap = null) {RedisConfig. redisGroupMap = RedisConfig. getRedisGroupMap ();} List <RedisCluster> clustersList = RedisConfig. redisGroupMap. get (CONT_CLUSTERNAME_PUBLICDATA); int arrayLength = clustersList. size (); // calculate the int clusterNo = getRedisNo (key, arrayLength) according to 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 ;} /*** obtain the publicdata redis key value Object ** @ param key * @ param objClass * @ param jedisGroup * @ return */public static Object getPublicDataObject (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 );} /*** obtain the publicdata redis key Value List <Entity> ** @ param key * @ param objClass * @ param jedisGroup * @ return */public static Object getPublicDataObjectByType (String key, type type, String selectdb) {Jedis jedis = getPublicDataJedis (key, GET_OPERATION, selectdb); String sObj = jedis. get (key); closeJedis (jedis); Gson gson = new Gson (); return gson. fromJson (sObj, type);}/*** get the redis Server Database Number ** @ param hashKey * @ return */public static int getRedisNo (String key, int arraySize) {long hashKey = hash (key); int redisNo = (int) (hashKey % arraySize); return redisNo ;} /*** calculate the hash value based on the key value ** @ param k * @ return */public static long hash (String k) {CRC32 crc32 = new CRC32 (); crc32.update (k. getBytes (); return crc32.getValue ();} /*** redis inserts an object into different databases 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_OPERATION); Gson gson = new Gson (); jedis. set (key, gson. toJson (insertObj); closeJedis (jedis );} /*** redis inserts an object into different databases based on the key value ** @ param key * @ param insertObj * @ param jedisGroup * @ param expire */public static void insertObject (string key, object insertObj, String jedisGroup, int expireSeconds) {Jedis jedis = getJedis (key, jedisGroup, INSERT_OPERATION); Gson gson = new Gson (); jedis. setex (key, expireSeconds, gson. toJson (insertObj); closeJedis (jedis );} /*** publicdata redis inserts the object to different databases based on the key value ** @ param key * @ param insertObj * @ param jedisGroup */public static void insertPublicDataObject (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 the object into different databases based on the key value, ** @ param key * @ param insertObj * @ param jedisGroup * @ param expireSeconds */public static void insertPublicDataObject (String key, Object insertObj, String selectdb, int expireSeconds) {Jedis jedis = getPublicDataJedis (key, INSERT_OPERATION, selectdb); Gson gson = new Gson (); jedis. setex (key, expireSeconds, gson. toJson (insertObj); closeJedis (jedis );} /*** update redis key timeout time ** @ param key * @ param jedisGroup * @ param expireSeconds */public static void resetExpireSeconds (String key, String jedisGroup, int expireSeconds) {Jedis jedis = getJedis (key, jedisGroup, GET_OPERATION); jedis. expire (key, expireSeconds); closeJedis (jedis );}}

5. Required jar packages

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.