Redis简介
Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。
Redis 与其他 key - value 缓存产品有以下三个特点:
Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用。
Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
Redis支持数据的备份,即master-slave模式的数据备份。
Redis运行在内存中,读的速度是110000次/s,写的速度是81000次/s 。
Redis安装与启动
Windows环境
下载地址:https://github.com/MSOpenTech/redis/releases。
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 D盘,解压后,将文件夹重新命名为 redis。
打开一个 cmd 窗口 使用cd命令切换目录到 D:\redis 运行 redis-server.exe redis.windows.conf 。
这时候另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了。
切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。
Linux环境
下载地址:http://redis.io/download,下载最新文档版本。
本教程使用的最新文档版本为 2.8.17,下载并安装:
$ wget http://download.redis.io/releases/redis-2.8.17.tar.gz
$ tar xzf redis-2.8.17.tar.gz
$ cd redis-2.8.17
$ make
make完后 redis-2.8.17目录下会出现编译后的redis服务程序redis-server,还有用于测试的客户端程序redis-cli,两个程序位于安装目录 src 目录下:
下面启动redis服务.
$ cd src
$ ./redis-server
注意这种方式启动redis 使用的是默认配置。也可以通过启动参数告诉redis使用指定配置文件使用下面命令启动。
$ cd src
$ ./redis-server redis.conf
redis.conf是一个默认的配置文件。我们可以根据需要使用自己的配置文件。
启动redis服务进程后,就可以使用测试客户端程序redis-cli和redis服务交互了。 比如:
$ cd src
$ ./redis-cli
redis> set foo bar
OK
redis> get foo
"bar"
Redis配置
Redis 的配置文件位于 Redis 安装目录下,文件名为 redis.conf。
你可以通过 CONFIG 命令查看或设置配置项。
redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
redis 127.0.0.1:6379> CONFIG GET loglevel
1) "loglevel"
2) "notice"
使用 * 号获取所有配置项:
redis 127.0.0.1:6379> CONFIG GET *
你可以通过修改 redis.conf 文件或使用 CONFIG set 命令来修改配置。
redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
redis 127.0.0.1:6379> CONFIG SET loglevel "notice"
OK
redis 127.0.0.1:6379> CONFIG GET loglevel
1) "loglevel"
2) "notice"
Redis 数据类型
Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
Redis命令
启动 redis 客户端,打开终端并输入命令 redis-cli。该命令会连接本地的 redis 服务。
如果需要在远程 redis 服务上执行命令,同样我们使用的也是 redis-cli 命令。
redis-cli -h ip地址 -p 端口号 -a 密码
Redis数据备份与恢复
redis Save 命令基本语法如下:
redis 127.0.0.1:6379> SAVE
该命令将在 redis 安装目录中创建dump.rdb文件。
如果需要恢复数据,只需将备份文件 (dump.rdb) 移动到 redis 安装目录并启动服务即可。
创建 redis 备份文件也可以使用命令 BGSAVE,该命令在后台执行。
Redis 安全
我们可以通过 redis 的配置文件设置密码参数,这样客户端连接到 redis 服务就需要密码验证,这样可以让你的 redis 服务更安全。
我们可以通过以下命令查看是否设置了密码验证:
127.0.0.1:6379> CONFIG get requirepass
1) "requirepass"
2) ""
默认情况下 requirepass 参数是空的,这就意味着你无需通过密码验证就可以连接到 redis 服务。
你可以通过以下命令来修改该参数:
127.0.0.1:6379> CONFIG set requirepass "tepu"
OK
127.0.0.1:6379> CONFIG get requirepass
1) "requirepass"
2) "tepu"
Java中如何使用redis
jedis是redis的java客户端,spring将redis连接池作为一个bean配置。
1、 maven导入相关包:pom.xml文件添加以下代码
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.5.1</version> </dependen>
2、在xxx.properties文件中配置redis相关信息
#redis settings redis.keyPrefix=jeesite redis.host=127.0.0.1 redis.port=6379
3、配置文件:spring-context-jedis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd" default-lazy-init="true"> <description>Jedis Configuration</description> <!-- 加载配置属性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:xxx.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="300" /> <!-- 最大能够保持idel状态的对象数 --> <property name="maxTotal" value="60000" /> <!-- 最大分配的对象数 --> <property name="testOnBorrow" value="true" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 --> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1" value="${redis.host}" /> <constructor-arg index="2" value="${redis.port}" type="int" /> <!-- <constructor-arg index="3" value="${redis.timeout}" type="int" /> <constructor-arg index="4" value="${redis.password}"/> <constructor-arg index="5" value="${redis.database}" type="int" /> <constructor-arg index="6" value="${redis.clientName}"/> --> </bean> </beans>
4、使用JedisUtil
package com.xx.common.utils; import java.util.List; import java.util.Map; import java.util.Set; import com.xx.common.config.Global; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException; /** * Jedis Cache 工具类 */ public class JedisUtils { private static Logger logger = LoggerFactory.getLogger(JedisUtils.class); private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class); public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix"); /** * 获取缓存 * @param key 键 * @return 值 */ public static String get(String key) { String value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.get(key); value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null; logger.debug("get {} = {}", key, value); } } catch (Exception e) { logger.warn("get {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Object getObject(String key) { Object value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = toObject(jedis.get(getBytesKey(key))); logger.debug("getObject {} = {}", key, value); } } catch (Exception e) { logger.warn("getObject {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String set(String key, String value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); result = jedis.set(key, value); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("set {} = {}", key, value); } catch (Exception e) { logger.warn("set {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setObject(String key, Object value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); result = jedis.set(getBytesKey(key), toBytes(value)); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObject {} = {}", key, value); } catch (Exception e) { logger.warn("setObject {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取List缓存 * @param key 键 * @return 值 */ public static List<String> getList(String key) { List<String> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.lrange(key, 0, -1); logger.debug("getList {} = {}", key, value); } } catch (Exception e) { logger.warn("getList {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取List缓存 * @param key 键 * @return 值 */ public static List<Object> getObjectList(String key) { List<Object> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { List<byte[]> list = jedis.lrange(getBytesKey(key), 0, -1); value = Lists.newArrayList(); for (byte[] bs : list){ value.add(toObject(bs)); } logger.debug("getObjectList {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectList {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置List缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setList(String key, List<String> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.rpush(key, (String[])value.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setList {} = {}", key, value); } catch (Exception e) { logger.warn("setList {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置List缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setObjectList(String key, List<Object> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } List<byte[]> list = Lists.newArrayList(); for (Object o : value){ list.add(toBytes(o)); } result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectList {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectList {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向List缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long listAdd(String key, String... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.rpush(key, value); logger.debug("listAdd {} = {}", key, value); } catch (Exception e) { logger.warn("listAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向List缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long listObjectAdd(String key, Object... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); List<byte[]> list = Lists.newArrayList(); for (Object o : value){ list.add(toBytes(o)); } result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray()); logger.debug("listObjectAdd {} = {}", key, value); } catch (Exception e) { logger.warn("listObjectAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Set<String> getSet(String key) { Set<String> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.smembers(key); logger.debug("getSet {} = {}", key, value); } } catch (Exception e) { logger.warn("getSet {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Set<Object> getObjectSet(String key) { Set<Object> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = Sets.newHashSet(); Set<byte[]> set = jedis.smembers(getBytesKey(key)); for (byte[] bs : set){ value.add(toObject(bs)); } logger.debug("getObjectSet {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectSet {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置Set缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setSet(String key, Set<String> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.sadd(key, (String[])value.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setSet {} = {}", key, value); } catch (Exception e) { logger.warn("setSet {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置Set缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setObjectSet(String key, Set<Object> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } Set<byte[]> set = Sets.newHashSet(); for (Object o : value){ set.add(toBytes(o)); } result = jedis.sadd(getBytesKey(key), (byte[][])set.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectSet {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectSet {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Set缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long setSetAdd(String key, String... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.sadd(key, value); logger.debug("setSetAdd {} = {}", key, value); } catch (Exception e) { logger.warn("setSetAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Set缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long setSetObjectAdd(String key, Object... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); Set<byte[]> set = Sets.newHashSet(); for (Object o : value){ set.add(toBytes(o)); } result = jedis.rpush(getBytesKey(key), (byte[][])set.toArray()); logger.debug("setSetObjectAdd {} = {}", key, value); } catch (Exception e) { logger.warn("setSetObjectAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取Map缓存 * @param key 键 * @return 值 */ public static Map<String, String> getMap(String key) { Map<String, String> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.hgetAll(key); logger.debug("getMap {} = {}", key, value); } } catch (Exception e) { logger.warn("getMap {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取Map缓存 * @param key 键 * @return 值 */ public static Map<String, Object> getObjectMap(String key) { Map<String, Object> value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = Maps.newHashMap(); Map<byte[], byte[]> map = jedis.hgetAll(getBytesKey(key)); for (Map.Entry<byte[], byte[]> e : map.entrySet()){ value.put(StringUtils.toString(e.getKey()), toObject(e.getValue())); } logger.debug("getObjectMap {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectMap {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置Map缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setMap(String key, Map<String, String> value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.hmset(key, value); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setMap {} = {}", key, value); } catch (Exception e) { logger.warn("setMap {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置Map缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setObjectMap(String key, Map<String, Object> value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } Map<byte[], byte[]> map = Maps.newHashMap(); for (Map.Entry<String, Object> e : value.entrySet()){ map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); } result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectMap {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectMap {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Map缓存中添加值 * @param key 键 * @param value 值 * @return */ public static String mapPut(String key, Map<String, String> value) { String result = null; Jedis jedis = null; try { jedis = getResource(); result = jedis.hmset(key, value); logger.debug("mapPut {} = {}", key, value); } catch (Exception e) { logger.warn("mapPut {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Map缓存中添加值 * @param key 键 * @param value 值 * @return */ public static String mapObjectPut(String key, Map<String, Object> value) { String result = null; Jedis jedis = null; try { jedis = getResource(); Map<byte[], byte[]> map = Maps.newHashMap(); for (Map.Entry<String, Object> e : value.entrySet()){ map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); } result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map); logger.debug("mapObjectPut {} = {}", key, value); } catch (Exception e) { logger.warn("mapObjectPut {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 移除Map缓存中的值 * @param key 键 * @param value 值 * @return */ public static long mapRemove(String key, String mapKey) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.hdel(key, mapKey); logger.debug("mapRemove {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapRemove {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 移除Map缓存中的值 * @param key 键 * @param value 值 * @return */ public static long mapObjectRemove(String key, String mapKey) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.hdel(getBytesKey(key), getBytesKey(mapKey)); logger.debug("mapObjectRemove {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapObjectRemove {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 判断Map缓存中的Key是否存在 * @param key 键 * @param value 值 * @return */ public static boolean mapExists(String key, String mapKey) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.hexists(key, mapKey); logger.debug("mapExists {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapExists {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 判断Map缓存中的Key是否存在 * @param key 键 * @param value 值 * @return */ public static boolean mapObjectExists(String key, String mapKey) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.hexists(getBytesKey(key), getBytesKey(mapKey)); logger.debug("mapObjectExists {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapObjectExists {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 删除缓存 * @param key 键 * @return */ public static long del(String key) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)){ result = jedis.del(key); logger.debug("del {}", key); }else{ logger.debug("del {} not exists", key); } } catch (Exception e) { logger.warn("del {}", key, e); } finally { returnResource(jedis); } return result; } /** * 删除缓存 * @param key 键 * @return */ public static long delObject(String key) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))){ result = jedis.del(getBytesKey(key)); logger.debug("delObject {}", key); }else{ logger.debug("delObject {} not exists", key); } } catch (Exception e) { logger.warn("delObject {}", key, e); } finally { returnResource(jedis); } return result; } /** * 缓存是否存在 * @param key 键 * @return */ public static boolean exists(String key) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.exists(key); logger.debug("exists {}", key); } catch (Exception e) { logger.warn("exists {}", key, e); } finally { returnResource(jedis); } return result; } /** * 缓存是否存在 * @param key 键 * @return */ public static boolean existsObject(String key) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.exists(getBytesKey(key)); logger.debug("existsObject {}", key); } catch (Exception e) { logger.warn("existsObject {}", key, e); } finally { returnResource(jedis); } return result; } /** * 获取资源 * @return * @throws JedisException */ public static Jedis getResource() throws JedisException { Jedis jedis = null; try { jedis = jedisPool.getResource(); // logger.debug("getResource.", jedis); } catch (JedisException e) { logger.warn("getResource.", e); returnBrokenResource(jedis); throw e; } return jedis; } /** * 归还资源 * @param jedis * @param isBroken */ public static void returnBrokenResource(Jedis jedis) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } } /** * 释放资源 * @param jedis * @param isBroken */ public static void returnResource(Jedis jedis) { if (jedis != null) { jedisPool.returnResource(jedis); } } /** * 获取byte[]类型Key * @param key * @return */ public static byte[] getBytesKey(Object object){ if(object instanceof String){ return StringUtils.getBytes((String)object); }else{ return ObjectUtils.serialize(object); } } /** * 获取byte[]类型Key * @param key * @return */ public static Object getObjectKey(byte[] key){ try{ return StringUtils.toString(key); }catch(UnsupportedOperationException uoe){ try{ return JedisUtils.toObject(key); }catch(UnsupportedOperationException uoe2){ uoe2.printStackTrace(); } } return null; } /** * Object转换byte[]类型 * @param key * @return */ public static byte[] toBytes(Object object){ return ObjectUtils.serialize(object); } /** * byte[]型转换Object * @param key * @return */ public static Object toObject(byte[] bytes){ return ObjectUtils.unserialize(bytes); } }