java操作redis数据库实例(redis集群)

1、配置redis集群

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <redisCluster>  
  3.     <!--userRoute -->  
  4.     <clusterGroup name="userRoute" selectdb="1">  
  5.         <server host="10.177.129.16" port="6379"></server>  
  6.         <server host="10.177.129.15" port="6379"></server>  
  7.     </clusterGroup>  
  8.     <!--sessionRoute -->  
  9.     <clusterGroup name="sessionRoute" selectdb="2">  
  10.         <server host="10.177.129.16" port="6379"></server>  
  11.         <server host="10.177.129.15" port="6379"></server>  
  12.     </clusterGroup>  
  13.     <!--publicData -->  
  14.     <clusterGroup name="publicData">  
  15.         <server host="10.177.129.16" port="6379"></server>  
  16.         <server host="10.177.129.15" port="6379"></server>  
  17.     </clusterGroup>  
  18. </redisCluster>  

2、创建redis连接属性实体类

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.isoftstone.cms.syscore.pojo;  
  2.   
  3. /** 
  4.  * redis连接属性 
  5.  * @author xiakai 
  6.  * 
  7.  */  
  8. public class RedisCluster   
  9. {  
  10.     private String selectdb;  
  11.     private String hostIp;  
  12.     private String  port;  
  13.       
  14.       
  15.     public String getSelectdb() {  
  16.         return selectdb;  
  17.     }  
  18.     public void setSelectdb(String selectdb) {  
  19.         this.selectdb = selectdb;  
  20.     }  
  21.     public String getHostIp() {  
  22.         return hostIp;  
  23.     }  
  24.     public void setHostIp(String hostIp) {  
  25.         this.hostIp = hostIp;  
  26.     }  
  27.     public String getPort() {  
  28.         return port;  
  29.     }  
  30.     public void setPort(String port) {  
  31.         this.port = port;  
  32.     }  
  33.   
  34.       
  35.       
  36.       
  37.   
  38. }  

3、解析redis集群配置

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.iss.itreasury.test.jedis;  
  2.   
  3.   
  4.   
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.HashMap;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.Set;  
  12.   
  13. import org.dom4j.Document;  
  14. import org.dom4j.DocumentException;  
  15. import org.dom4j.Element;  
  16. import org.dom4j.io.SAXReader;  
  17. import org.springframework.core.io.ClassPathResource;   
  18. import org.springframework.core.io.Resource;   
  19. import org.springframework.core.io.support.EncodedResource;  
  20.   
  21.   
  22.   
  23.   
  24. /** 
  25.  * 解析redis集群配置 
  26.  * @author xiakai 
  27.  * 
  28.  */  
  29. public class RedisConfig {  
  30.       
  31. public static Map<String,List<RedisCluster>> redisGroupMap = null;  
  32.   
  33. //有参构造函数  
  34. public RedisConfig()  
  35. {  
  36.       
  37. }  
  38.   
  39.   
  40. //获取所有clusterGroup组的键值对  
  41. public static Map<String,List<RedisCluster>> getRedisGroupMap(){  
  42.     //读取xml文件  
  43.     Document document=readXmlFile();  
  44.     //获得clusterGroup节点的key 和 list  
  45.     if(redisGroupMap == null)  
  46.     {  
  47.         redisGroupMap=getMapByItemsGroup(document);  
  48.     }  
  49.       
  50.     return redisGroupMap;  
  51. }  
  52.   
  53.   
  54. //读取redisConfig配置文件  
  55. private static Document readXmlFile(){  
  56.     //创建读入对象  
  57.     SAXReader reader = new SAXReader();  
  58.     //创建document实例  
  59.     Document doc=null;  
  60.     try {  
  61.     //从类路径下加载文件redisConfig.xml    
  62.     Resource resource = new ClassPathResource("redisClusterConfig.xml");   
  63.     //指定文件资源对应的编码格式(UTF-8),这样才能正确读取文件的内容,而不会出现乱码  
  64.     EncodedResource encodeResource = new EncodedResource(resource,"UTF-8");   
  65.     doc = reader.read(encodeResource.getReader());  
  66.     }   
  67.     catch (IOException e) {  
  68.         System.out.println("无法读取系统配置文件redisConfig.xml,可能该文件不存在");  
  69.           
  70.     } catch (DocumentException e) {  
  71.         System.out.println("解析redisConfig.xml文件出现异常");  
  72.           
  73.     }  
  74.     return doc;  
  75.   
  76. }  
  77.   
  78. //读取xml节点,返回节点为redisGroup的Map  
  79. private  static Map<String,List<RedisCluster>> getMapByItemsGroup(Document document){  
  80.     Map<String,List<RedisCluster>> itemmap=new HashMap<String,List<RedisCluster>>();  
  81.     try{  
  82.         //获得根节点  
  83.         Element root=document.getRootElement();  
  84.         //获得根节点下所有子节点clusterGroup的list  
  85.         List itemsList=root.selectNodes("./clusterGroup");  
  86.         for(int i=0;i<itemsList.size();i++){  
  87.         //获得节点Items  
  88.         Element items=(Element)itemsList.get(i);  
  89.         String groupName=items.attribute("name").getText();  
  90.         String selectdb = items.attribute("selectdb")==null?"":items.attribute("selectdb").getText();  
  91. //      if(groupName!=null&&groupName.equals(this.getGroupName())){  
  92.              //获得clusterGroup下所有子节点service的list  
  93.              List itemList=items.elements();  
  94.              //获得service节点的值  
  95.              List<RedisCluster> redisClusterList = getItemList(itemList,selectdb);  
  96.                
  97.              itemmap.put(groupName, redisClusterList);  
  98. //      }  
  99.           
  100.         }  
  101.     }  
  102.     catch(Exception e){  
  103.           
  104.     }  
  105.     return itemmap;  
  106. }  
  107.   
  108.   
  109. //获得所有Item下节点的redis服务节点  
  110. private static List<RedisCluster> getItemList(List itemList,String selectdb){  
  111.       
  112.     List<RedisCluster> redisClusterList = new ArrayList<RedisCluster>();  
  113.     for(int i=0;i<itemList.size();i++){  
  114.         //获得节点server  
  115.         Element item=(Element)itemList.get(i);  
  116.         String hostIp =  item.attribute("host").getText();  
  117.         String port = item.attribute("port").getText();  
  118.           
  119.         RedisCluster redisCluster =new RedisCluster();  
  120.         redisCluster.setHostIp(hostIp);  
  121.         redisCluster.setPort(port);  
  122.         redisCluster.setSelectdb(selectdb);  
  123.           
  124.         redisClusterList.add(redisCluster);  
  125.    }  
  126.     return redisClusterList;  
  127.       
  128.       
  129. }  
  130.   
  131. public static void main(String[] args) {  
  132.     getRedisGroupMap();  
  133.     //JedisUtil.insertPublicDataObject("user1", "张三", JedisUtil.ONLINE_USER);  
  134.     //JedisUtil.insertPublicDataObject("user2", "李四", JedisUtil.ONLINE_USER);  
  135.     //JedisUtil.insertPublicDataObject("user3", "王五", JedisUtil.ONLINE_USER);  
  136.   
  137.       Set s = JedisUtil.getAllSet(JedisUtil.ONLINE_USER);  
  138.       Iterator it = s.iterator();      
  139.       while (it.hasNext()) {  
  140.        String key = (String) it.next();  
  141.        String value = JedisUtil.getString(key,JedisUtil.ONLINE_USER);  
  142.        System.out.println(key + value);  
  143.       }  
  144.     String test = JedisUtil.getString("user1",JedisUtil.ONLINE_USER);  
  145.     System.out.println(test);  
  146.       
  147. }  
  148. }  


4、操作redis数据库的工具类


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.isoftstone.cms.syscore.utils;  
  2.   
  3. import java.lang.reflect.Type;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6. import java.util.zip.CRC32;  
  7.   
  8. import redis.clients.jedis.Jedis;  
  9. import redis.clients.jedis.exceptions.JedisConnectionException;  
  10.   
  11. import com.google.gson.Gson;  
  12. import com.isoftstone.cms.syscore.pojo.RedisCluster;  
  13.   
  14. public class JedisUtil {  
  15.       
  16.     // 数据库  
  17.     public static final String STORE_LOGINUSER = "4";// 商户登陆用户  
  18.     public static final String STORE_INFO = "5";// 商户状态 商户购买服务有效期  
  19.     public static final String CHECK_CODE = "6";// 验证码  
  20.     public static final String MENU = "7";// 全部菜单  
  21.     public static final String SERVICE = "8";// 服务收费信息  
  22.     public static final String STORE_LOGINKEY = "9";// 初始化登录公钥 私钥对  
  23.     // 固定key  
  24.     public static final String ALL_MENU_KEY = "ALL_MENU_KEY";  
  25.     public static final String BUY_SERVICE_KEY = "BUY_SERVICE_KEY";// 服务收费购买key  
  26.     public static final String ALL_SERVICE_KEY = "ALL_SERVICE_KEY";//所有服务  
  27.     public static final String MENU_AUTHORITY = "MENU_AUTHORITY";// 菜单权限  
  28.     public static final String STORE_MENU_KEY = "STORE_MENU_KEY";// 需要商户分配的业务菜单  
  29.     public static final String STORE_SERVICE_KEY = "STORE_SERVICE_KEY";// 商户收费key  
  30.     public static final String SYSTE_MENU_KEY = "SYSTE_MENU_KEY";// 系统管理菜单key  
  31.   
  32.     // jedis服务组业务类型  
  33.     public static final String CONT_CLUSTERNAME_PUBLICDATA = "publicData";  
  34.     public static final String CONT_CLUSTERNAME_SESSIONROUTE = "sessionRoute";  
  35.     public static final String CONT_CLUSTERNAME_USERROUTE = "userRoute";  
  36.       
  37.     // 操作方式 0 插入 1获取 2 删除  
  38.     public static final long INSERT_OPERATION = 0;  
  39.     public static final long GET_OPERATION = 1;  
  40.     public static final long DELETE_OPERATION = 2;  
  41.   
  42.     // 验证码过期秒数  
  43.     public static final int CHECKCODE_EXPIRESECONDS = 5*60;  
  44.     // session过期秒数  
  45.     public static final int EXPIRESECONDS = 30 * 60;  
  46.   
  47.     private static void closeJedis(Jedis jedis) {  
  48.         try {  
  49.             jedis.quit();  
  50.         } catch (JedisConnectionException e) {  
  51.             e.printStackTrace();  
  52.         }  
  53.         jedis.disconnect();  
  54.     }  
  55.       
  56.     /** 
  57.      * 根据Key获取字符串 
  58.      * 
  59.      * @param key 
  60.      * @param jedisGroup 
  61.      */  
  62.     public static String getString(String key, String selectdb) {  
  63.         Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb);  
  64.         return jedis.get(key);  
  65.     }  
  66.       
  67.     /** 
  68.      * 获取所有数据set 
  69.      * @param selectdb 
  70.      * @return 
  71.      */  
  72.     public static Set getAllSet(String selectdb) {  
  73.         Jedis jedis = getDataJedis(GET_OPERATION, selectdb);  
  74.         return jedis.keys("*");  
  75.     }  
  76.       
  77.     /** 
  78.      * 默认取配置文件的第一个数据库 
  79.      * @param operation 
  80.      * @param selectdb 
  81.      * @return 
  82.      */  
  83.     private static Jedis getDataJedis(long operation, String selectdb) {  
  84.         if (RedisConfig.redisGroupMap == null) {  
  85.             RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap();  
  86.         }  
  87.         List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(CONT_CLUSTERNAME_PUBLICDATA);  
  88.   
  89.         int clusterNo = 0;//默认存到第一个  
  90.   
  91.         RedisCluster cluster = clustersList.get(clusterNo);  
  92.         Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort()));  
  93.         jedis.select(Integer.valueOf(selectdb));  
  94.         return jedis;  
  95.     }  
  96.   
  97.   
  98.     /** 
  99.      * 删除数据 
  100.      * 
  101.      * @param key 
  102.      * @param jedisGroup 
  103.      */  
  104.     public static void deleteObject(String key, String jedisGroup) {  
  105.         Jedis jedis = getJedis(key, jedisGroup, DELETE_OPERATION);  
  106.         jedis.del(key);  
  107.         closeJedis(jedis);  
  108.     }  
  109.   
  110.     /** 
  111.      * 删除公共数据 
  112.      * 
  113.      * @param key 
  114.      * @param objClass 
  115.      * @param selectdb 
  116.      */  
  117.     public static void deletePublicDataObject(String key, String selectdb) {  
  118.         Jedis jedis = getPublicDataJedis(key, DELETE_OPERATION, selectdb);  
  119.         jedis.del(key);  
  120.         closeJedis(jedis);  
  121.     }  
  122.   
  123.     /** 
  124.      * 获取jedis的库实例 
  125.      * 
  126.      * @param key 
  127.      * @param jedisGroup 
  128.      * @param operation 
  129.      * @return 
  130.      */  
  131.     private static Jedis getJedis(String key, String jedisGroup, long operation) {  
  132.         if (RedisConfig.redisGroupMap == null) {  
  133.             RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap();  
  134.         }  
  135.         List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(jedisGroup);  
  136.         int arrayLength = clustersList.size();  
  137.         // 根据key值算出该信息应该存入到那个  
  138.         int clusterNo = getRedisNo(key, arrayLength);  
  139.   
  140.         RedisCluster cluster = clustersList.get(clusterNo);  
  141.         Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort()));  
  142.         jedis.select(Integer.valueOf(cluster.getSelectdb()));  
  143.         return jedis;  
  144.     }  
  145.   
  146.     /** 
  147.      * redis key值获取对象 
  148.      * 
  149.      * @param key 
  150.      * @param objClass 
  151.      * @param jedisGroup 
  152.      * @return 
  153.      */  
  154.     public static Object getObject(String key, Class objClass, String jedisGroup) {  
  155.         Jedis jedis = getJedis(key, jedisGroup, GET_OPERATION);  
  156.   
  157.         String sObj = jedis.get(key);  
  158.         closeJedis(jedis);  
  159.         Gson gson = new Gson();  
  160.         return gson.fromJson(sObj, objClass);  
  161.   
  162.     }  
  163.   
  164.     /** 
  165.      * 获取公共数据jedis的库实例 
  166.      * 
  167.      * @param key 
  168.      * @param jedisGroup 
  169.      * @param operation 
  170.      * @return 
  171.      */  
  172.     private static Jedis getPublicDataJedis(String key, long operation, String selectdb) {  
  173.         if (RedisConfig.redisGroupMap == null) {  
  174.             RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap();  
  175.         }  
  176.         List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(CONT_CLUSTERNAME_PUBLICDATA);  
  177.         int arrayLength = clustersList.size();  
  178.         // 根据key值算出该信息应该存入到那个  
  179.         int clusterNo = getRedisNo(key, arrayLength);  
  180.   
  181.         RedisCluster cluster = clustersList.get(clusterNo);  
  182.         Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort()));  
  183.         jedis.select(Integer.valueOf(selectdb));  
  184.         return jedis;  
  185.     }  
  186.   
  187.     /** 
  188.      * publicdata redis key值获取对象 
  189.      * 
  190.      * @param key 
  191.      * @param objClass 
  192.      * @param jedisGroup 
  193.      * @return 
  194.      */  
  195.     public static Object getPublicDataObject(String key, Class objClass, String selectdb) {  
  196.         Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb);  
  197.   
  198.         String sObj = jedis.get(key);  
  199.         closeJedis(jedis);  
  200.         Gson gson = new Gson();  
  201.         return gson.fromJson(sObj, objClass);  
  202.   
  203.     }  
  204.   
  205.     /** 
  206.      * publicdata redis key值获取对象 List<Entity> 
  207.      * 
  208.      * @param key 
  209.      * @param objClass 
  210.      * @param jedisGroup 
  211.      * @return 
  212.      */  
  213.     public static Object getPublicDataObjectByType(String key, Type type, String selectdb) {  
  214.         Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb);  
  215.   
  216.         String sObj = jedis.get(key);  
  217.         closeJedis(jedis);  
  218.         Gson gson = new Gson();  
  219.         return gson.fromJson(sObj, type);  
  220.     }  
  221.   
  222.     /** 
  223.      * 获取redis服务器库编号 
  224.      * 
  225.      * @param hashKey 
  226.      * @return 
  227.      */  
  228.     public static int getRedisNo(String key, int arraySize) {  
  229.         long hashKey = hash(key);  
  230.         int redisNo = (int) (hashKey % arraySize);  
  231.         return redisNo;  
  232.     }  
  233.   
  234.     /** 
  235.      * 根据key值算出hash值 
  236.      * 
  237.      * @param k 
  238.      * @return 
  239.      */  
  240.     public static long hash(String k) {  
  241.         CRC32 crc32 = new CRC32();  
  242.         crc32.update(k.getBytes());  
  243.         return crc32.getValue();  
  244.     }  
  245.   
  246.     /** 
  247.      * redis 根据key值将对象插入到不同的库中 
  248.      * 
  249.      * @param key 
  250.      * @param insertObj 
  251.      * @param jedisGroup 
  252.      */  
  253.     public static void insertObject(String key, Object insertObj, String jedisGroup) {  
  254.   
  255.         Jedis jedis = getJedis(key, jedisGroup, INSERT_OPERATION);  
  256.         Gson gson = new Gson();  
  257.         jedis.set(key, gson.toJson(insertObj));  
  258.         closeJedis(jedis);  
  259.     }  
  260.   
  261.     /** 
  262.      * redis 根据key值将对象插入到不同的库中 
  263.      * 
  264.      * @param key 
  265.      * @param insertObj 
  266.      * @param jedisGroup 
  267.      * @param expire 
  268.      */  
  269.     public static void insertObject(String key, Object insertObj, String jedisGroup, int expireSeconds) {  
  270.   
  271.         Jedis jedis = getJedis(key, jedisGroup, INSERT_OPERATION);  
  272.         Gson gson = new Gson();  
  273.         jedis.setex(key, expireSeconds, gson.toJson(insertObj));  
  274.         closeJedis(jedis);  
  275.     }  
  276.   
  277.     /** 
  278.      * publicdata redis 根据key值将对象插入到不同的库中 
  279.      * 
  280.      * @param key 
  281.      * @param insertObj 
  282.      * @param jedisGroup 
  283.      */  
  284.     public static void insertPublicDataObject(String key, Object insertObj, String selectdb) {  
  285.   
  286.         Jedis jedis = getPublicDataJedis(key, INSERT_OPERATION, selectdb);  
  287.         Gson gson = new Gson();  
  288.         jedis.set(key, gson.toJson(insertObj));  
  289.         closeJedis(jedis);  
  290.     }  
  291.   
  292.     /** 
  293.      * publicdata redis 根据key值将对象插入到不同的库中, 
  294.      * 
  295.      * @param key 
  296.      * @param insertObj 
  297.      * @param jedisGroup 
  298.      * @param expireSeconds 
  299.      */  
  300.     public static void insertPublicDataObject(String key, Object insertObj, String selectdb, int expireSeconds) {  
  301.         Jedis jedis = getPublicDataJedis(key, INSERT_OPERATION, selectdb);  
  302.         Gson gson = new Gson();  
  303.         jedis.setex(key, expireSeconds, gson.toJson(insertObj));  
  304.         closeJedis(jedis);  
  305.     }  
  306.   
  307.     /** 
  308.      * 更新redis中key的超时时间 
  309.      * 
  310.      * @param key 
  311.      * @param jedisGroup 
  312.      * @param expireSeconds 
  313.      */  
  314.     public static void resetExpireSeconds(String key, String jedisGroup, int expireSeconds) {  
  315.         Jedis jedis = getJedis(key, jedisGroup, GET_OPERATION);  
  316.         jedis.expire(key, expireSeconds);  
  317.         closeJedis(jedis);  
  318.     }  
  319.   
  320. }  


5、所需jar包



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值