定义:
redis是一个key-value 存储系统 。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list( 链表 )、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些 数据类型 都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
依赖:
需要依赖下面几个jar包(spring3.2.9)
spring-session-1.3.3.RELEASE.jar spring-session-data-redis-2.0.4.RELEASE.jar jedis-2.9.0.jar spring-data-redis-1.5.2.RELEASE.jar 注:pom依赖见http://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis/2.0.4.RELEASE
基本数据类型:
创建redis配置spring文件:String: set name “cgd” Get name List: lpush mylist a lpush mylist b Lrange mylist 0 10 Hash: hmset myhash flied1 “a” flied2 “b” Hget myhash flied1 Set: sadd myset a Smembers myset Zset: zadd myzset 0 redis zadd myzset 3 redis zadd myzset 1 redis Zrangebyscore myzset 0 10
redis工具封装:<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName"> <!-- session共享设置 --> <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="3600"></property> </bean> <!-- redis配置 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <!-- <property name="locations"> <list> <value>classpath*:redis.properties</value> </list> </property> --> </bean> <!-- redis连接池 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大连接数 --> <property name="maxTotal" value="${redis.maxTotal}"></property> <!-- 最大空闲连接数 --> <property name="maxIdle" value="${redis.maxIdle}"></property> <!-- 连接最小空闲时间 --> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property> <!-- 每次释放连接的最大数 --> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property> <!-- 释放连接的扫描间隔 --> <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property> <!-- 获取连接时最大等待毫秒数,小于零:阻塞不确定时间,默认-1 --> <property name="maxWaitMillis" value="1500"></property> <!-- 连接空闲多久后释放,当空闲时间>该值 且空闲连接>最大空闲连接数时直接释放 --> <property name="softMinEvictableIdleTimeMillis" value="10000"></property> <!-- 获取连接时检测有效性 --> <property name="testWhileIdle" value="true"></property> <!-- 连接耗尽时是否阻塞,false报异常,true阻塞知道超时,默认true --> <property name="blockWhenExhausted" value="false"></property> </bean> <!-- redis连接工厂 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="${redis.hostName}"></property> <property name="port" value="${redis.port}"></property> <property name="password" value="${redis.password}"></property> <property name="timeout" value="${redis.timeout}"></property> <property name="usePool" value="${redis.usePool}"></property> </bean> <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> </bean> </beans>
/** * redis 基本操作工具类 * @author cgd * * @param <T> */ @Service("redisCacheUtil") public class RedisCacheUtil<T> { @Autowired @Qualifier("jedisTemplate") public RedisTemplate redisTemplate; /** * 缓存基本的对象,Integer、String、实体类等 * * @param key * 缓存的键值 * @param value * 缓存的值 * @return 缓存的对象 */ public <T> ValueOperations<String, T> setCacheObject(String key, T value) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); operation.set(key, value); return operation; } /** * 缓存基本的对象并设置缓存有效时间(秒),Integer、String、实体类等 * @param key * @param value * @param time * @return */ public <T> ValueOperations<String, T> setCacheObject(String key, T value,long timeout) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); operation.set(key, value, timeout, TimeUnit.SECONDS); return operation; } /** * 获得缓存的基本对象。 * * @param key * 缓存键值 * @param operation * @return 缓存键值对应的数据 */ public <T> T getCacheObject(String key) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); return operation.get(key); } /** * 检测key对应缓存是否存在 * @param key * @return */ public Boolean hasCache(String key) { return redisTemplate.hasKey(key); } /** * 缓存List数据 * * @param key * 缓存的键值 * @param dataList * 待缓存的List数据 * @return 缓存的对象 */ public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList) { ListOperations listOperation = redisTemplate.opsForList(); if (null != dataList) { int size = dataList.size(); for (int i = 0; i < size; i++) { listOperation.rightPush(key, dataList.get(i)); } } return listOperation; } /** * 获得缓存的list对象 * * @param key * 缓存的键值 * @return 缓存键值对应的数据 */ public <T> List<T> getCacheList(String key) { List<T> dataList = new ArrayList<T>(); ListOperations<String, T> listOperation = redisTemplate.opsForList(); Long size = listOperation.size(key); for (int i = 0; i < size; i++) { dataList.add((T) listOperation.leftPop(key)); } return dataList; } /** * 缓存Set * * @param key * 缓存键值 * @param dataSet * 缓存的数据 * @return 缓存数据的对象 */ public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) { BoundSetOperations<String, T> setOperation = redisTemplate .boundSetOps(key); Iterator<T> it = dataSet.iterator(); while (it.hasNext()) { setOperation.add(it.next()); } return setOperation; } /** * 获得缓存的set * * @param key * @param operation * @return */ public Set<T> getCacheSet(String key) { Set<T> dataSet = new HashSet<T>(); BoundSetOperations<String, T> operation = redisTemplate .boundSetOps(key); Long size = operation.size(); for (int i = 0; i < size; i++) { dataSet.add(operation.pop()); } return dataSet; } /** * 缓存Map * * @param key * @param dataMap * @return */ public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<String, T> entry : dataMap.entrySet()) { hashOperations.put(key, entry.getKey(), entry.getValue()); } } return hashOperations; } /** * 获得缓存的Map * * @param key * @param hashOperation * @return */ public <T> Map<String, T> getCacheMap(String key) { Map<String, T> map = redisTemplate.opsForHash().entries(key); return map; } /** * 缓存Map * * @param key * @param dataMap * @return */ public <T> HashOperations<String, Integer, T> setCacheIntegerMap( String key, Map<Integer, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<Integer, T> entry : dataMap.entrySet()) { hashOperations.put(key, entry.getKey(), entry.getValue()); } } return hashOperations; } /** * 获得缓存的Map * * @param key * @return */ public <T> Map<Integer, T> getCacheIntegerMap(String key) { Map<Integer, T> map = redisTemplate.opsForHash().entries(key); return map; } /** * 删除指定的缓存对象 * * @param key * @return */ public void deleteCache(String key) { redisTemplate.delete(key); } /** * 删除指定的缓存对象集合 * * @param key * @return */ public void deleteCache(Collection keys) { redisTemplate.delete(keys); } /** * 异步延时删除指定的缓存对象(毫秒) * * @param key * @return */ public void deleteCacheDelay(String key,long timeout) { new Thread(){ public void run(){ try { Thread.sleep(timeout); redisTemplate.delete(key); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } /** * 设置缓存过期时间(秒) * * @param key * @return */ public void expireCache(String key,int timeout) { redisTemplate.expire(key, timeout, TimeUnit.SECONDS); } }