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

1、配置redis集群

<?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、创建redis连接属性实体类

package com.isoftstone.cms.syscore.pojo;

/**
 * redis连接属性
 * @author xiakai
 *
 */
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、解析redis集群配置

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;




/**
 * 解析redis集群配置
 * @author xiakai
 *
 */
public class RedisConfig {
	
public static Map<String,List<RedisCluster>> redisGroupMap = null;

//有参构造函数
public RedisConfig()
{
	
}


//获取所有clusterGroup组的键值对
public static Map<String,List<RedisCluster>> getRedisGroupMap(){
	//读取xml文件
	Document document=readXmlFile();
	//获得clusterGroup节点的key 和 list
	if(redisGroupMap == null)
	{
		redisGroupMap=getMapByItemsGroup(document);
	}
	
	return redisGroupMap;
}


//读取redisConfig配置文件
private static Document readXmlFile(){
    //创建读入对象
    SAXReader reader = new SAXReader();
    //创建document实例
    Document doc=null;
    try {
    //从类路径下加载文件redisConfig.xml	
    Resource resource = new ClassPathResource("redisClusterConfig.xml"); 
    //指定文件资源对应的编码格式(UTF-8),这样才能正确读取文件的内容,而不会出现乱码
    EncodedResource encodeResource = new EncodedResource(resource,"UTF-8"); 
    doc = reader.read(encodeResource.getReader());
	} 
    catch (IOException e) {
    	System.out.println("无法读取系统配置文件redisConfig.xml,可能该文件不存在");
		
	} catch (DocumentException e) {
		System.out.println("解析redisConfig.xml文件出现异常");
		
	}
	return doc;

}

//读取xml节点,返回节点为redisGroup的Map
private  static Map<String,List<RedisCluster>> getMapByItemsGroup(Document document){
	Map<String,List<RedisCluster>> itemmap=new HashMap<String,List<RedisCluster>>();
	try{
		//获得根节点
		Element root=document.getRootElement();
		//获得根节点下所有子节点clusterGroup的list
		List itemsList=root.selectNodes("./clusterGroup");
		for(int i=0;i<itemsList.size();i++){
		//获得节点Items
		Element 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())){
			 //获得clusterGroup下所有子节点service的list
			 List itemList=items.elements();
			 //获得service节点的值
			 List<RedisCluster> redisClusterList = getItemList(itemList,selectdb);
			 
			 itemmap.put(groupName, redisClusterList);
//		}
	    
		}
	}
	catch(Exception e){
		
	}
	return itemmap;
}


//获得所有Item下节点的redis服务节点
private static List<RedisCluster> getItemList(List itemList,String selectdb){
	
	List<RedisCluster> redisClusterList = new ArrayList<RedisCluster>();
	for(int i=0;i<itemList.size();i++){
		//获得节点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", "张三", JedisUtil.ONLINE_USER);
	//JedisUtil.insertPublicDataObject("user2", "李四", JedisUtil.ONLINE_USER);
	//JedisUtil.insertPublicDataObject("user3", "王五", 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、操作redis数据库的工具类


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 {
	
	// 数据库
	public static final String STORE_LOGINUSER = "4";// 商户登陆用户
	public static final String STORE_INFO = "5";// 商户状态 商户购买服务有效期
	public static final String CHECK_CODE = "6";// 验证码
	public static final String MENU = "7";// 全部菜单
	public static final String SERVICE = "8";// 服务收费信息
	public static final String STORE_LOGINKEY = "9";// 初始化登录公钥 私钥对
	// 固定key
	public static final String ALL_MENU_KEY = "ALL_MENU_KEY";
	public static final String BUY_SERVICE_KEY = "BUY_SERVICE_KEY";// 服务收费购买key
	public static final String ALL_SERVICE_KEY = "ALL_SERVICE_KEY";//所有服务
	public static final String MENU_AUTHORITY = "MENU_AUTHORITY";// 菜单权限
	public static final String STORE_MENU_KEY = "STORE_MENU_KEY";// 需要商户分配的业务菜单
	public static final String STORE_SERVICE_KEY = "STORE_SERVICE_KEY";// 商户收费key
	public static final String SYSTE_MENU_KEY = "SYSTE_MENU_KEY";// 系统管理菜单key

	// jedis服务组业务类型
	public static final String CONT_CLUSTERNAME_PUBLICDATA = "publicData";
	public static final String CONT_CLUSTERNAME_SESSIONROUTE = "sessionRoute";
	public static final String CONT_CLUSTERNAME_USERROUTE = "userRoute";
	
	// 操作方式 0 插入 1获取 2 删除
	public static final long INSERT_OPERATION = 0;
	public static final long GET_OPERATION = 1;
	public static final long DELETE_OPERATION = 2;

	// 验证码过期秒数
	public static final int CHECKCODE_EXPIRESECONDS = 5*60;
	// session过期秒数
	public static final int EXPIRESECONDS = 30 * 60;

	private static void closeJedis(Jedis jedis) {
		try {
			jedis.quit();
		} catch (JedisConnectionException e) {
			e.printStackTrace();
		}
		jedis.disconnect();
	}
	
	/**
	 * 根据Key获取字符串
	 *
	 * @param key
	 * @param jedisGroup
	 */
	public static String getString(String key, String selectdb) {
		Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb);
		return jedis.get(key);
	}
	
	/**
	 * 获取所有数据set
	 * @param selectdb
	 * @return
	 */
	public static Set getAllSet(String selectdb) {
		Jedis jedis = getDataJedis(GET_OPERATION, selectdb);
		return jedis.keys("*");
	}
	
	/**
	 * 默认取配置文件的第一个数据库
	 * @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;//默认存到第一个

		RedisCluster cluster = clustersList.get(clusterNo);
		Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort()));
		jedis.select(Integer.valueOf(selectdb));
		return jedis;
	}


	/**
	 * 删除数据
	 *
	 * @param key
	 * @param jedisGroup
	 */
	public static void deleteObject(String key, String jedisGroup) {
		Jedis jedis = getJedis(key, jedisGroup, DELETE_OPERATION);
		jedis.del(key);
		closeJedis(jedis);
	}

	/**
	 * 删除公共数据
	 *
	 * @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);
	}

	/**
	 * 获取jedis的库实例
	 *
	 * @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();
		// 根据key值算出该信息应该存入到那个
		int clusterNo = getRedisNo(key, arrayLength);

		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值获取对象
	 *
	 * @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);

	}

	/**
	 * 获取公共数据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();
		// 根据key值算出该信息应该存入到那个
		int clusterNo = getRedisNo(key, arrayLength);

		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值获取对象
	 *
	 * @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);

	}

	/**
	 * publicdata redis key值获取对象 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);
	}

	/**
	 * 获取redis服务器库编号
	 *
	 * @param hashKey
	 * @return
	 */
	public static int getRedisNo(String key, int arraySize) {
		long hashKey = hash(key);
		int redisNo = (int) (hashKey % arraySize);
		return redisNo;
	}

	/**
	 * 根据key值算出hash值
	 *
	 * @param k
	 * @return
	 */
	public static long hash(String k) {
		CRC32 crc32 = new CRC32();
		crc32.update(k.getBytes());
		return crc32.getValue();
	}

	/**
	 * redis 根据key值将对象插入到不同的库中
	 *
	 * @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 根据key值将对象插入到不同的库中
	 *
	 * @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 根据key值将对象插入到不同的库中
	 *
	 * @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 根据key值将对象插入到不同的库中,
	 *
	 * @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);
	}

	/**
	 * 更新redis中key的超时时间
	 *
	 * @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、所需jar包



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值