码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA对Redis的使用

时间:2016-05-27 11:26:30      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

package com.redis.learn.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisTool {

	//Redis服务器地址
	private static String address = "localhost";
	//Redis服务器端口号
	private static int port = 6379;
	//访问密码
	private static String auth = null;
	//可用连接实例的最大数目,默认值为8;
	//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
	//private static final int MAX_ACTIVE = 1024;
	
	//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
	private static int MAX_IDLE = 10;
	//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
	private static int MAX_WAIT = 10000;
	private static int TIMEOUT = 10000;
	//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
	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);
	}
	
	/**
	 * 获取Jedis客户端
	 * @return
	 */
	public static Jedis getJedis() {
		Jedis jedis = null;
		if(null != jedisPool) {
			jedis = jedisPool.getResource();
		}
		return jedis;
	}
	
	/**
	 * 返还资源
	 * @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相关操作
 * @author xianglj
 */
public class RedisUtil {
	
	private static final Charset UTF_8 = Charset.forName("utf-8");

	/**
	 * 向redis新增字符串键值对
	 * @param key
	 * @param value
	 */
	public static boolean setString(String key, String value) {
		if(null == key || value == null ) {
			return false;
		}
		
		return setBytes(key.getBytes(UTF_8), value.getBytes(UTF_8));
	}
	
	/**
	 * 向Redis中储存键值对的byte数组,最长不能超过1GB的字节
	 * @param key 键
	 * @param value 值
	 * @return
	 */
	public static boolean setBytes(byte[] key, byte[] value) {
		if(null == key || null == value) {
			return false;
		}
		
		Jedis jedis = RedisTool.getJedis();
		String statusCode = jedis.set(key, value);
		System.out.println("状态码:(" + statusCode + ")");
		RedisTool.returnResource(jedis);
		return true;
	}
	
	/**
	 * 获取String类型的值
	 * @param 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);
	}
	
	/**
	 * 获取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;
	}
	
	/**
	 * 删除某个键,如果键被删除,再次请求相同键时,返回null
	 * @param key
	 */
	private static boolean del(byte[] key) {
		if(null == key) {
			return true;
		}
		
		Jedis jedis = RedisTool.getJedis();
		jedis.del(key);
		return true;
	}
	
	/**
	 * 操作字符串类型(String),删除键
	 * @param key
	 * @return
	 */
	public static boolean delString(String key) {
		if(null == key) {
			return true;
		}
		
		byte[] k = key.getBytes(UTF_8);
		return del(k);
	}
	
	/**
	 * 批量插入缓存:<br>
	 * key,value,key,value<br>
	 * 例如<br>
	 * name,johnny,age,12<br>
	 * 则会新增name=johnny,age=12的缓存,如果在缓存中已经存在相同的缓存,则会立即更新。
	 * @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;
	}
	
	/**
	 * 插入一个简单类型的Map
	 * @param key
	 * @param map
	 */
	public static void addMap(String key, Map<String, String> map) {
		if(null == 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) {
			return;
		}
		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) {
			return;
		}
		Jedis jedis = RedisTool.getJedis();
		jedis.hsetnx(key, field, value);
		RedisTool.returnResource(jedis);
	}
	
	/**
	 * 向Redis中插入一个Map的值
	 * @param key
	 * @param mapByte
	 */
	public static void addMap(byte[] key, Map<byte[], byte[]> mapByte) {
		if(null == key || null == mapByte) {
			return;
		}
		
		Jedis jedis = RedisTool.getJedis();
		//总是会返回OK,并不会执行失败
		String status = jedis.hmset(key, mapByte);
		System.out.println("执行状态:" + status);
		RedisTool.returnResource(jedis);
	}
	
	/**
	 * 获取Map中的值,只能够
	 * @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 = jedis.hmget(key, fields);
		}
		
		RedisTool.returnResource(jedis);
		return rtnList;
	}
	
	/**
	 * 获取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 = jedis.hmget(key, fields);
		}
		
		return rtnList;
	}
	
	/**
	 * 向Redis中添加set集合
	 * @param key
	 * @param values
	 */
	public static void addSet(String key, String ... values) {
		if(null == key || 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);
	}
	
	/**
	 * 获取所有的值
	 * @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;
	}
	
	/**
	 * 判断是否Set集合中包含元素
	 * @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;
	}
	
	/**
	 * 返回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;
	}
	
	/**
	 * 向list集合中添加元素
	 * @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);
	}
	
	/**
	 * 向list集合中添加元素
	 * @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);
	}
	
	/**
	 * 获取start到end范围的值,超出list的范围,不会抛出异常
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<String> 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;
	}
	
	/**
	 * 获取start到end范围的值,超出list的范围,不会抛出异常
	 * @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");

	@Test
	public void testString() {
		System.err.println("测试String类型开始>>\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("从Redis中获取name:>>>\r\n\t");
		String val = RedisUtil.getString(key);
		System.out.println("输出:\r\n\t" + val);
		
		System.out.println("从Redis中获取name bytes:>>>>\r\n\t");
		byte[] bytes = RedisUtil.getBytes(key.getBytes(UTF_8));
		System.out.println("输出bytes:\r\n\t" + Arrays.toString(bytes));
		val = new String(bytes, UTF_8);
		System.out.println("转换后String:\r\n\t" + val);
		
		System.out.println("删除name的键:\r\n\t");
		RedisUtil.delString(key);
		val = RedisUtil.getString(key);
		System.out.println("再次获取:" + (val==null?"该键已被删除..":val));
	}
	
	@Test
	public void testMap() {
		
		System.err.println("测试Redis For Map 开始:>>>>");
		
		//简单的string map
		Map<String, String> strMap = new HashMap<String, String>();
		//复杂点的map
		Map<byte[], byte[]> bytesMap = new HashMap<byte[], byte[]>();
		
		//测试储存新的地址
		strMap.put("OS", "Windows 10");
		strMap.put("Language", "ch");
		strMap.put("Tool", "Redis For Windows");
		String skey = "String For Redis";
		RedisUtil.addMap(skey, strMap);
		
		//从获取所有的值
		List<String> sList = RedisUtil.getMapVal(skey);
		System.out.println("所有结果值:" + sList);
		
		//按照给出的field顺序给出值
		sList = RedisUtil.getMapVal(skey, "Tool", "OS", "Language", "dd");
		//发现取出的值和输入的field的顺序一致
		System.out.println("输出值[Tool, OS, Language, dd]:\r\n\t"+ sList);
		
		//尝试在Redis中存储对象
		Person person = new Person("Johnny", 23, "男");
		//序列化对象
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		ObjectInputStream bis = null;
		try {
			oos = new ObjectOutputStream(baos);
			//创建对象
			oos.writeObject(person);
			//获取序列化之后的字节码
			byte[] bytes = baos.toByteArray();
			bytesMap.put(person.getName().getBytes(UTF_8), bytes);
			RedisUtil.addMap(person.getName().getBytes(UTF_8), bytesMap);
			
			//从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("获取到对象:" + 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();
			}
		}
		
		//向已经存在的key中新增键值对
		RedisUtil.addMapVal(person.getName().getBytes(UTF_8), "AddTest".getBytes(UTF_8), "Test Redis Adding A Val For Exist Key".getBytes(UTF_8));
		//获取刚插入的值
		System.out.println("获取刚插入的值:\r\n\t" + 
		new String(RedisUtil.getMapVal(person.getName().getBytes(UTF_8), "AddTest".getBytes(UTF_8)).get(0)));
		
		//尝试向不存在的Key中插值
		RedisUtil.addMapVal("AddNewKey", "AddNewMapKey", "AddNewMapVal");
		//能够获取到值,因此也说明在进行不存在key的插值时,会自动创建对象的键值对以保存。
		System.out.println("尝试获取刚插入的值:\r\n\t" + RedisUtil.getMapVal("AddNewKey", "AddNewMapKey"));
	}
	
	@Test
	public void testSet() {
		System.err.println("测试Redis For Set 开始:>>>>>>>");
		//向Redis添加元素
		RedisUtil.addSet("AddNewSet", "set1", "set2", "set3");
		//获取set中的值
		System.out.println("Set集合的长度:\r\n\t" + RedisUtil.getSetLength("AddNewSet"));
		System.out.println("Set集合元素:\r\n\t" + RedisUtil.getSetVals("AddNewSet"));
		//尝试移除元素
		RedisUtil.delSetVal("AddNewSet", "set2");
		System.out.println("Set集合的长度:\r\n\t" + RedisUtil.getSetLength("AddNewSet"));
		System.out.println("Set集合元素:\r\n\t" + RedisUtil.getSetVals("AddNewSet"));
		
		//判断是否包含元素
		System.out.println("是否包含set2的值:" + RedisUtil.isSetContain("AddNewSet", "set2"));
		System.out.println("是否包含set2的值:" + RedisUtil.isSetContain("AddNewSet", "set3"));
	}
	
	@Test
	public void testList() {
		System.err.println("测试Redis For List 开始:>>>>>>");
		//向List中添加元素
		RedisUtil.addList("ValList", "List1", "List2", "List3");
		//获取List中的值
		System.out.println("Redis For List中的值为:" + RedisUtil.getListAll("ValList"));
		//弹出list的第一个元素
		System.out.println("弹出第一个元素:" + RedisUtil.popList("ValList"));
		System.out.println("Redis For List中的值为:" + RedisUtil.getListAll("ValList"));
	}
}

class Person implements Serializable {
	private static final long serialVersionUID = 8737363017319228700L;
	private String name;
	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 age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}
以上是做了Redis的一些基本操作的封装和测试类,仅供参考

JAVA对Redis的使用

标签:

原文地址:http://blog.csdn.net/u011425751/article/details/51508247

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!