Java连接redis的使用示例

Redis是开源的key-value存储工具,redis通常用来存储结构化的数据,因为redis的key可以包含String、hash、listset和sorted list。

Redisserver目前最稳定的版本是2.8.9,可以到官网http://redis.io/download下载。根据机器的类型及位数下载对应的版本安装即可,reids支持linux和windows操作系统。

Redisclient支持多种语言,包括:c、C++、C#、php、java、python、go等语言,根据自己的开发语言,选择合适的redis client版本类型即可。我是使用java语言开发的,针对java语言,redis client也提供了多种客户端支持,按照推荐类型依次是:Jedis、Redisson、JRedis、JDBC-Redis、RJC、redis-protocol、aredis、lettuce。前两种类型是比较推荐的,我们采用了Redisson类型版本作为redisclient的使用。

Redisson的源码工程所在位置:https://github.com/mrniko/redisson。这里有使用示例及一些介绍,这里不再详细的介绍。

Redis Java客户端jedis工具类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Builder;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.SafeEncoder;

/**
 * The RedisUtil represents
 * @version $Id$
 * @author fengjc
 */
public class RedisUtil {

	/**
	 * 数据源
	 */
	private ShardedJedisPool shardedJedisPool;

	/** ======================================Strings====================================== */

	/**
	 * Set the string value as value of the key. The string can‘t be longer than
	 * 1073741824 bytes (1 GB).
	 * Time complexity: O(1)
	 * @param key
	 * @param value
	 * @return Status code reply
	 */
	public String setString(String key, String value) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		String status = jedis.set(key, value);
		this.shardedJedisPool.returnResource(jedis);
		return status;
	}

	/**
	 * Get the value of the specified key. If the key does not exist the special
	 * value ‘nil‘ is returned. If the value stored at key is not a string an
	 * error is returned because GET can only handle string values.
	 * Time complexity: O(1)
	 * @param key
	 * @return Bulk reply
	 */
	public String getString(String key) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		String value = jedis.get(key);
		this.shardedJedisPool.returnResource(jedis);
		return value;
	}

	/**
	 * This Stirng的批量更新
	 * @param pairs
	 */
	public List<Object> batchSetString(final List<Pair<String, String>> pairs) {
		final ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<Object> status = jedis.pipelined(new ShardedJedisPipeline() {

			@Override
			public void execute() {
				for (Pair<String, String> pair : pairs) {
					set(pair.getKey(), pair.getValue());
				}
			}
		});
		this.shardedJedisPool.returnResource(jedis);
		return status;
	}

	/**
	 * This String的批量获得
	 * @param keys
	 * @return
	 */
	public List<String> batchGetString(final List<String> keys) {
		final ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {

			@Override
			public void execute() {
				for (String key : keys) {
					get(key);
				}
			}
		});
		this.shardedJedisPool.returnResource(jedis);
		List<String> rtnDataList = new ArrayList<String>();
		for (Object data : dataList) {
			rtnDataList.add(STRING.build(data));
		}
		return rtnDataList;
	}

	/** ======================================Hashes====================================== */

	/**
	 * Set the specified hash field to the specified value.
	 * If key does not exist, a new key holding a hash is created.
	 * Time complexity: O(1)
	 * @param key
	 * @param field
	 * @param value
	 * @return If the field already exists, and the HSET just produced an update
	 *         of the value, 0 is returned, otherwise if a new field is created
	 *         1 is returned.
	 */
	public long hashSet(String key, String field, String value) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		long count = jedis.hset(key, field, value);
		this.shardedJedisPool.returnResource(jedis);
		return count;
	}

	/**
	 * If key holds a hash, retrieve the value associated to the specified
	 * field.
	 * If the field is not found or the key does not exist, a special ‘nil‘
	 * value is returned.
	 * Time complexity:O(1)
	 * @param key
	 * @param field
	 * @return Bulk reply
	 */
	public String hashGet(String key, String field) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		String value = jedis.hget(key, field);
		this.shardedJedisPool.returnResource(jedis);
		return value;
	}

	/**
	 * Set the respective fields to the respective values. HMSET replaces old
	 * values with new values.
	 * If key does not exist, a new key holding a hash is created.
	 * Time complexity: O(N) (with N being the number of fields)
	 * @param key
	 * @param hash
	 * @return Return OK or Exception if hash is empty
	 */
	public String hashMultipleSet(String key, Map<String, String> hash) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		String status = jedis.hmset(key, hash);
		this.shardedJedisPool.returnResource(jedis);
		return status;
	}

	/**
	 * Retrieve the values associated to the specified fields.
	 * If some of the specified fields do not exist, nil values are returned.
	 * Non existing keys are considered like empty hashes.
	 * Time complexity: O(N) (with N being the number of fields)
	 * @param key
	 * @param fields
	 * @return Multi Bulk Reply specifically a list of all the values associated
	 *         with the specified fields, in the same order of the request.
	 */
	public List<String> hashMultipleGet(String key, String... fields) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<String> dataList = jedis.hmget(key, fields);
		this.shardedJedisPool.returnResource(jedis);
		return dataList;
	}

	/**
	 * This 批量的HashMultipleSet
	 * @param pairs
	 * @return
	 */
	public List<Object> batchHashMultipleSet(final List<Pair<String, Map<String, String>>> pairs) {
		final ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<Object> status = jedis.pipelined(new ShardedJedisPipeline() {

			@Override
			public void execute() {
				for (Pair<String, Map<String, String>> pair : pairs) {
					hmset(pair.getKey(), pair.getValue());
				}
			}
		});
		this.shardedJedisPool.returnResource(jedis);
		return status;
	}

	/**
	 * This 批量的HashMultipleGet
	 * @param pairs
	 * @return
	 */
	public List<List<String>> batchHashMultipleGet(final List<Pair<String, String[]>> pairs) {
		final ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {

			@Override
			public void execute() {
				for (Pair<String, String[]> pair : pairs) {
					hmget(pair.getKey(), pair.getValue());
				}
			}
		});
		this.shardedJedisPool.returnResource(jedis);
		List<List<String>> rtnDataList = new ArrayList<List<String>>();
		for (Object data : dataList) {
			rtnDataList.add(STRING_LIST.build(data));
		}
		return rtnDataList;
	}

	/**
	 * Return all the fields and associated values in a hash.
	 * Time complexity: O(N), where N is the total number of entries
	 * @param key
	 * @return All the fields and values contained into a hash.
	 */
	public Map<String, String> hashGetAll(String key) {
		ShardedJedis jedis = this.shardedJedisPool.getResource();
		Map<String, String> hash = jedis.hgetAll(key);
		this.shardedJedisPool.returnResource(jedis);
		return hash;
	}

	/**
	 * This 批量的hashMultipleGet
	 * @param keys
	 * @return
	 */
	public List<Map<String, String>> batchHashGetAll(final List<String> keys) {
		final ShardedJedis jedis = this.shardedJedisPool.getResource();
		List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {

			@Override
			public void execute() {
				for (String key : keys) {
					hgetAll(key);
				}
			}
		});
		this.shardedJedisPool.returnResource(jedis);
		List<Map<String, String>> rtnDataList = new ArrayList<Map<String, String>>();
		for (Object data : dataList) {
			rtnDataList.add(STRING_MAP.build(data));
		}
		return rtnDataList;
	}

	/** ======================================Builder====================================== */

	public static final Builder<Double> DOUBLE = new Builder<Double>() {

		@Override
		public Double build(Object data) {
			return Double.valueOf(STRING.build(data));
		}

		@Override
		public String toString() {
			return "double";
		}
	};

	public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {

		@Override
		public Boolean build(Object data) {
			return ((Long) data) == 1;
		}

		@Override
		public String toString() {
			return "boolean";
		}
	};

	public static final Builder<Long> LONG = new Builder<Long>() {

		@Override
		public Long build(Object data) {
			return (Long) data;
		}

		@Override
		public String toString() {
			return "long";
		}

	};

	public static final Builder<String> STRING = new Builder<String>() {

		@Override
		public String build(Object data) {
			return SafeEncoder.encode((byte[]) data);
		}

		@Override
		public String toString() {
			return "string";
		}

	};

	public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {

		@Override
		@SuppressWarnings("unchecked")
		public List<String> build(Object data) {
			if (null == data) {
				return null;
			}
			List<byte[]> l = (List<byte[]>) data;
			final ArrayList<String> result = new ArrayList<String>(l.size());
			for (final byte[] barray : l) {
				if (barray == null) {
					result.add(null);
				} else {
					result.add(SafeEncoder.encode(barray));
				}
			}
			return result;
		}

		@Override
		public String toString() {
			return "List<String>";
		}

	};

	public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {

		@Override
		@SuppressWarnings("unchecked")
		public Map<String, String> build(Object data) {
			final List<byte[]> flatHash = (List<byte[]>) data;
			final Map<String, String> hash = new HashMap<String, String>();
			final Iterator<byte[]> iterator = flatHash.iterator();
			while (iterator.hasNext()) {
				hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()));
			}

			return hash;
		}

		@Override
		public String toString() {
			return "Map<String, String>";
		}

	};

	public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {

		@Override
		@SuppressWarnings("unchecked")
		public Set<String> build(Object data) {
			if (null == data) {
				return null;
			}
			List<byte[]> l = (List<byte[]>) data;
			final Set<String> result = new HashSet<String>(l.size());
			for (final byte[] barray : l) {
				if (barray == null) {
					result.add(null);
				} else {
					result.add(SafeEncoder.encode(barray));
				}
			}
			return result;
		}

		@Override
		public String toString() {
			return "Set<String>";
		}

	};

	public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {

		@Override
		@SuppressWarnings("unchecked")
		public Set<String> build(Object data) {
			if (null == data) {
				return null;
			}
			List<byte[]> l = (List<byte[]>) data;
			final Set<String> result = new LinkedHashSet<String>(l.size());
			for (final byte[] barray : l) {
				if (barray == null) {
					result.add(null);
				} else {
					result.add(SafeEncoder.encode(barray));
				}
			}
			return result;
		}

		@Override
		public String toString() {
			return "ZSet<String>";
		}

	};

	/** ======================================Other====================================== */

	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}

	/**
	 * This 构造Pair
	 * @param key
	 * @param value
	 * @return
	 */
	public <K, V> Pair<K, V> makePair(K key, V value) {
		return new Pair<K, V>(key, value);
	}

	/**
	 * The Pair represents 键值对
	 * @version $Id$
	 * @author fengjc
	 * @param <K>
	 * @param <V>
	 */
	public class Pair<K, V> {

		private K key;
		private V value;

		public Pair(K key, V value) {
			this.key = key;
			this.value = value;
		}

		public K getKey() {
			return this.key;
		}

		public void setKey(K key) {
			this.key = key;
		}

		public V getValue() {
			return this.value;
		}

		public void setValue(V value) {
			this.value = value;
		}

	}
}

原文参考:http://blog.csdn.net/wgw335363240/article/details/24471311

时间: 2024-10-11 19:40:03

Java连接redis的使用示例的相关文章

java连接redis问题

package com.guo.redis; import redis.clients.jedis.Jedis; public class Redis_1 { public static void main(String[] args) { // TODO Auto-generated method stub //连接到远程的redis服务 Jedis jedis = new Jedis("192.168.80.1",6379); //权限 验证 // jedis.auth("

java 连接Redis及demo

java连接linux Redis遇到的问题 昨天在Linux搭建了Redis服务,今天使用java连接测试了一下.要想使用java连接redis服务,就离不开jedis-2.6.1.jar.使用jedis连接redis十分方便.下面我们测试一下是否连接上redis服务: package com.coinvs.redis.util;import redis.clients.jedis.Jedis;//import redis.clients.jedis.Jedis;public class Ra

一个非常标准的Java连接Oracle数据库的示例代码

最基本的Oracle数据库连接代码(只针对Oracle11g): 1.右键项目->构建路径->配置构建路径,选择第三项"库",然后点击"添加外部Jar",选择"D:\Oracle\app\oracle\product\11.2.0\server \jdbc\lib\ojdbc6_g.jar"(注:D:\Oracle为数据库的安装路径). 2.以下代码为非常标准的Oracle数据库连接代码示例: /** * 一个非常标准的连接Oracl

java连接redis

类似于java连接mysql需要包 java连接redis同样也需要包 jedis-2.1.0.jar是java用来连接redis的包 1.将包引入即可 2. public void redisTest(){ Jedis jedis=new Jedis("127.0.0.1", 6379); jedis.set("greeting", "hello world"); String greeting = jedis.get("greeti

Java连接redis的使用演示样例

Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sorted list. Redisserver眼下最稳定的版本号是2.8.9,能够到官网http://redis.io/download下载.依据机器的类型及位数下载相应的版本号安装就可以,reids支持linux和windows操作系统. Redisclient支持多种语言,包含:c.C++.C#.php.java.python.go等语

java连接redis,实现订阅发布遇到的问题

我在使用的时候redis是安装在本机虚拟机上,使用java连接时遇到一些错误,归纳需要改动的地方如下: 1.redis的配置文件默认是绑定了127.0.0.1的ip,需要到redis.conf中找到这一行,注释掉 2.redis默认不允许非本机客户端连接,本身又是没有密码的,需要设置一个登录密码,用密码连接 设置密码命令:config set requirepass xxx,密码设置之后需要认证一下才能正常使用get获取数据:auth xxx,后面是刚才设置的密码 3.java程序连接redis

Java连接Redis之redis的增删改查

一.新建一个maven工程,工程可以以jar的形式或war都行,然后导入正确的依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs

学习记录04 --- 使用java连接redis数据库进行操作

现在先简单的尝试下java如何连接上redis数据库 首先我们需要一个jedis.jar架包,我下载的是2.9.0的版本 附上下载地址,点击我下载 开始我们的常规操作,打开idea,导入架包,emmmmm,感觉这次会写的特别简短 先导包 import redis.clients.jedis.Jedis; 我们需要连接redis数据库的话,都是依赖于jedis对象而来的,我们先得new出一个jedis对象 //new一个Jedis对象,连接redis数据库 Jedis jedis = new Je

Java连接Oracle数据库的示例代码

最基本的Oracle数据库连接代码(只针对Oracle11g): 1.右键项目->构建路径 ->配置构建路径,选择第三项“库”,然后点击“添加外部Jar”,选择 “D:\Oracle\app\oracle\product\11.2.0\server \jdbc\lib\ojdbc6_g.jar”(注:D:\Oracle为数据库的安装路径). 2.以下代码为非常标准的Oracle数据库连接代码示例: /** * 一个非常标准的连接Oracle数据库的示例代码 */public void test