redis缓存管理

一、Redis介绍

  1. Redis简介。

    Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

  2. Redis优势
  • 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
  • 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
  • 原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。
  • 丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。

二、Redis安装

1. Redis服务端安装

Window 下安装

下载地址:https://github.com/MSOpenTech/redis/releases。 
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 C 盘,解压后,将文件夹重新命名为 redis。 
打开一个 cmd 窗口 使用cd命令切换目录到 C:\redis 运行 redis-server.exe redis.windows.conf 。 
如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:

 
这时候另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了。 
切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。 
设置键值对 set myKey abc 
取出键值对 get myKey 

Linux 下安装

下载地址:http://redis.io/download,下载最新文档版本。

本教程使用的最新文档版本为 2.8.17,下载并安装:

$ wget http://download.redis.io/releases/redis-2.8.17.tar.gz 
tarxzfredis−2.8.17.tar.gztarxzfredis−2.8.17.tar.gz cd redis-2.8.17 
$ make


make完后 redis-2.8.17目录下会出现编译后的redis服务程序redis-server,还有用于测试的客户端程序redis-cli,两个程序位于安装目录 src 目录下:

下面启动redis服务.

注意这种方式启动redis 使用的是默认配置。也可以通过启动参数告诉redis使用指定配置文件使用下面命令启动。

cdsrccdsrc ./redis-server redis.conf

redis.conf是一个默认的配置文件。我们可以根据需要使用自己的配置文件。 

启动redis服务进程后,就可以使用测试客户端程序redis-cli和redis服务交互了。 比如:

cdsrccdsrc ./redis-cli 
redis> set foo bar 
OK 
redis> get foo 
“bar”


注意:默认情况下,redis只能访问本机127.0.0.1.若需要开启远程访问,则需要修改配置文件redis.conf(windows下,修改redis.windows.conf)。 

  • 注释掉bind 127.0.0.1可以使所有的ip访问redis
  • 找到“protected-mode yes”并改为“protected-mode no”
  • 输入命令 redis-cli -h 192.168.0.227 -p 6379 ($ redis-cli -h host -p port -a password)

2. Redis管理客户端安装

客户端下载

三、Redis+Spring应用

1.增加maven

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>

2. 增加spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd ">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties,classpath:nriat.properties" />
 
<!-- 单个redis配置 -->
<!-- redis连接池的配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="10"></property> <!-- 最大分配的对象数 -->
<property name="maxIdle" value="10"></property> <!-- 最大能够保持idel状态的对象数 -->
<property name="minIdle" value="2"></property>
<property name="maxWaitMillis" value="15000"></property>
<property name="minEvictableIdleTimeMillis" value="300000"></property>
<property name="numTestsPerEvictionRun" value="3"></property>
<property name="timeBetweenEvictionRunsMillis" value="60000"></property>
<property name="testOnBorrow" value="true"></property> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
<property name="testOnReturn" value="true"></property>
<property name="testWhileIdle" value="true"></property>
</bean>
<!-- redis的连接池pool,不是必选项:timeout/password -->
<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"/> <!-- port -->
<constructor-arg index="3" value="15000" type="int"/> <!-- timeout -->
<constructor-arg index="4" value="${redis.password}"/> <!-- password -->
</bean>
 
 
<!-- 以下是spring-data-redis配置方式 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="${redis.host}"></property>
<property name="port" value="${redis.port}"></property>
<property name="password" value="${redis.password}"></property>
<property name="poolConfig" ref="jedisPoolConfig"></property>
</bean>
<!-- SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
就是因为序列化策略的不同,即使是同一个key用不同的Template去序列化,结果是不同的。所以根据key去删除数据的时候就出现了删除失败的问题。
-->
<!-- redis 序列化策略 ,通常情况下key值采用String序列化策略, -->
<!-- 如果不指定序列化策略,StringRedisTemplate的key和value都将采用String序列化策略; -->
<!-- 但是RedisTemplate的key和value都将采用JDK序列化 这样就会出现采用不同template保存的数据不能用同一个template删除的问题 -->
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer" ref="stringRedisSerializer" />
<property name="hashKeySerializer" ref="stringRedisSerializer" />
<property name="valueSerializer" ref="stringRedisSerializer"/>
</bean>
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<!-- redis jedisCluster集群配置 -->
<!-- <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig" >
<property name="maxWaitMillis" value="-1" />
<property name="maxTotal" value="1000" />
<property name="minIdle" value="8" />
<property name="maxIdle" value="100" />
</bean>
<bean id="jedisCluster" class="cn.zsmy.palmdoctor.redis.JedisClusterFactory">
<property name="addressConfig">
<value>classpath:redis.properties</value>
</property>
<property name="addressKeyPrefix" value="address" /> 属性文件里 key的前缀
<property name="password" value="123456" /> redis密码
<property name="timeout" value="300000" />
<property name="maxRedirections" value="6" />
<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
</bean> -->
</beans>

3. 增加 redisTemplate工具类

package com.nriat.base.cache;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nriat.base.framework.SpringContextUtil;
import com.nriat.utils.CacheKeyUtils;
import com.nriat.utils.JSONUtils;
import com.nriat.utils.StringUtil;

/**
 * 
 * redis工具类
 * 
 * @author: pc175
 * @date: 2018年2月6日 上午10:39:26 @note: redis 的key 请注意格式:以“
 *        object-type:id:field”格式为准,比如”user:1000:password”
 * @Other: 参考https://www.thinksaas.cn/group/topic/789095/
 *
 */
public class RedisManager {

	private static StringRedisTemplate stringRedisTemplate = (StringRedisTemplate) SpringContextUtil
			.getBean("stringRedisTemplate");
	// private static RedisTemplate<String, Object> redisTemplate =
	// (RedisTemplate<String, Object>)
	// SpringContextUtil.getBean("redisTemplate");

	/**
	 * session 失效时间 单位:秒
	 */
	public static final long SESSION_EXPIRE_TIME = 36000L;

	/**
	 * 删除缓存<br>
	 * 根据key精确匹配删除
	 * 
	 * @param key
	 */
	@SuppressWarnings("unchecked")
	public static void del(String... key) {
		if (key != null && key.length > 0) {
			if (key.length == 1) {
				stringRedisTemplate.delete(key[0]);
			} else {
				stringRedisTemplate.delete(CollectionUtils.arrayToList(key));
			}
		}
	}

	/**
	 * 批量删除<br>
	 * (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删)
	 * 
	 * @param pattern
	 */
	public static void batchDel(String... pattern) {
		for (String kp : pattern) {
			stringRedisTemplate.delete(stringRedisTemplate.keys(kp + "*"));
		}
	}

	/**
	 * 取得缓存(int型)
	 * 
	 * @param key
	 * @return
	 */
	public static Integer getInt(String key) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (StringUtil.notEmpty(value)) {
			return Integer.valueOf(value);
		}
		return null;
	}

	/**
	 * 取得缓存(字符串类型)
	 * 
	 * @param key
	 * @return
	 */
	public static String getStr(String key) {
		return stringRedisTemplate.boundValueOps(key).get();
	}

	/**
	 * 取得缓存(字符串类型)
	 * 
	 * @param key
	 * @return
	 */
	public static String getStr(String key, boolean retain) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (!retain) {
			stringRedisTemplate.delete(key);
		}
		return value;
	}

	/**
	 * 获取缓存<br>
	 * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
	 * 
	 * @param key
	 * @return
	 */
	public static Object getObj(String key) {
		return stringRedisTemplate.boundValueOps(key).get();
	}

	/**
	 * 获取缓存<br>
	 * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
	 * 
	 * @param key
	 * @return
	 */
	public static Object getObjSession(String key, String sessionId) {
		key = CacheKeyUtils.getSessionKey(key, sessionId);
		return stringRedisTemplate.boundValueOps(key).get();
	}

	/**
	 * 获取缓存<br>
	 * 注:java 8种基本类型的数据请直接使用get(String key, Class<T> clazz)取值
	 * 
	 * @param key
	 * @param retain
	 *            是否保留
	 * @return
	 */
	public static Object getObj(String key, boolean retain) {
		Object obj = stringRedisTemplate.boundValueOps(key).get();
		if (!retain) {
			stringRedisTemplate.delete(key);
		}
		return obj;
	}

	/**
	 * 获取缓存<br>
	 * 注:该方法暂不支持Character数据类型
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String key, Class<T> clazz) {
		return (T) stringRedisTemplate.boundValueOps(key).get();
	}

	/**
	 * 获取缓存<br>
	 * 注:该方法暂不支持Character数据类型
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 */
	public static <T> T getSession(String key, String sessionId, Class<T> clazz) {
		key = CacheKeyUtils.getSessionKey(key, sessionId);
		return (T) stringRedisTemplate.boundValueOps(key).get();
	}

	/**
	 * 获取缓存json对象<br>
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 */
	public static <T> T getJson(String key, Class<T> clazz) {
		return JSONUtils.GsonToBean(stringRedisTemplate.boundValueOps(key).get(), clazz);
	}

	/**
	 * 获取缓存json对象<br>
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 */
	public static <T> T getJsonSession(String key, Class<T> clazz, String sessionId) {
		key = CacheKeyUtils.getSessionKey(key, sessionId);
		return JSONUtils.GsonToBean(stringRedisTemplate.boundValueOps(key).get(), clazz);
	}

	/**
	 * 将value对象写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void set(String key, Object value, long time) {
		if (value.getClass().equals(String.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Integer.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Double.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Float.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Short.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Long.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Boolean.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		}
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	/**
	 * 将value对象写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void setSession(String key, String sessionId, Object value) {
		if (value == null) {
			return;
		}
		key = CacheKeyUtils.getSessionKey(key, sessionId);

		if (value.getClass().equals(String.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Integer.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Double.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Float.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Short.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Long.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Boolean.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		}

		stringRedisTemplate.expire(key, RedisManager.SESSION_EXPIRE_TIME, TimeUnit.SECONDS);

	}

	/**
	 * 将value对象以JSON格式写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void setJsonSession(String key, String sessionId, Object value) {
		key = CacheKeyUtils.getSessionKey(key, sessionId);
		stringRedisTemplate.opsForValue().set(key, JSONUtils.GsonString(value));
		// 设置过期时间
		stringRedisTemplate.expire(key, RedisManager.SESSION_EXPIRE_TIME, TimeUnit.SECONDS);

	}

	/**
	 * 将value对象以JSON格式写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void setJson(String key, Object value, long time) {
		stringRedisTemplate.opsForValue().set(key, JSONUtils.GsonString(value));
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	/**
	 * 更新key对象field的值
	 * 
	 * @param key
	 *            缓存key
	 * @param field
	 *            缓存对象field
	 * @param value
	 *            缓存对象field值
	 */
	public static void setJsonField(String key, String field, String value) {
		JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());
		obj.put(field, value);
		stringRedisTemplate.opsForValue().set(key, obj.toJSONString());
	}

	/**
	 * 递减操作
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static double decr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, -by);
	}

	/**
	 * 递增操作
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static double incr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, by);
	}

	/**
	 * 获取double类型值
	 * 
	 * @param key
	 * @return
	 */
	public static double getDouble(String key) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (StringUtil.notEmpty(value)) {
			return Double.valueOf(value);
		}
		return 0d;
	}

	/**
	 * 设置double类型值
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void setDouble(String key, double value, long time) {
		stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	/**
	 * 设置double类型值
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public static void setInt(String key, int value, long time) {
		stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	/**
	 * 将map写入缓存
	 * 
	 * @param key
	 * @param map
	 * @param time
	 *            失效时间(秒)
	 */
	public static <T> void setMap(String key, Map<String, T> map, long time) {
		stringRedisTemplate.opsForHash().putAll(key, map);
	}

	/**
	 * 将map写入缓存
	 * 
	 * @param key
	 * @param map
	 * @param time
	 *            失效时间(秒)
	 */
	@SuppressWarnings("unchecked")
	public static <T> void setMap(String key, T obj, long time) {
		Map<String, String> map = (Map<String, String>) JSONUtils.parseObject(obj, Map.class);
		stringRedisTemplate.opsForHash().putAll(key, map);
	}

	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 * @param map
	 */
	public static <T> void addMap(String key, Map<String, T> map) {
		stringRedisTemplate.opsForHash().putAll(key, map);
	}

	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 *            cache对象key
	 * @param field
	 *            map对应的key
	 * @param value
	 *            值
	 */
	public static void addMap(String key, String field, String value) {
		stringRedisTemplate.opsForHash().put(key, field, value);
	}

	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 *            cache对象key
	 * @param field
	 *            map对应的key
	 * @param obj
	 *            对象
	 */
	public static <T> void addMap(String key, String field, T obj) {
		stringRedisTemplate.opsForHash().put(key, field, obj);
	}

	/**
	 * 获取map缓存
	 * 
	 * @param key
	 * @param clazz
	 * @return
	 */
	public static <T> Map<String, T> mget(String key, Class<T> clazz) {
		BoundHashOperations<String, String, T> boundHashOperations = stringRedisTemplate.boundHashOps(key);
		return boundHashOperations.entries();
	}

	/**
	 * 获取map缓存
	 * 
	 * @param key
	 * @param clazz
	 * @return
	 */
	public static <T> T getMap(String key, Class<T> clazz) {
		BoundHashOperations<String, String, String> boundHashOperations = stringRedisTemplate.boundHashOps(key);
		Map<String, String> map = boundHashOperations.entries();
		return JSONUtils.parseObject(map, clazz);
	}

	/**
	 * 获取map缓存中的某个对象
	 * 
	 * @param key
	 * @param field
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getMapField(String key, String field, Class<T> clazz) {
		return (T) stringRedisTemplate.boundHashOps(key).get(field);
	}

	/**
	 * 删除map中的某个对象
	 * 
	 * @author lh
	 * @date 2016年8月10日
	 * @param key
	 *            map对应的key
	 * @param field
	 *            map中该对象的key
	 */
	public void delMapField(String key, String... field) {
		BoundHashOperations<String, String, ?> boundHashOperations = stringRedisTemplate.boundHashOps(key);
		boundHashOperations.delete(field);
	}

	/**
	 * 指定缓存的失效时间
	 * 
	 * @author FangJun
	 * @date 2016年8月14日
	 * @param key
	 *            缓存KEY
	 * @param time
	 *            失效时间(秒)
	 */
	public static void expire(String key, long time) {
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	/**
	 * 添加set
	 * 
	 * @param key
	 * @param value
	 */
	public static void sadd(String key, String... value) {
		stringRedisTemplate.boundSetOps(key).add(value);
	}

	/**
	 * 删除set集合中的对象
	 * 
	 * @param key
	 * @param value
	 */
	public static void srem(String key, String... value) {
		stringRedisTemplate.boundSetOps(key).remove(value);
	}

	/**
	 * set重命名
	 * 
	 * @param oldkey
	 * @param newkey
	 */
	public static void srename(String oldkey, String newkey) {
		stringRedisTemplate.boundSetOps(oldkey).rename(newkey);
	}

	/**
	 * 模糊查询keys
	 * 
	 * @param pattern
	 * @return
	 */
	public static Set<String> keys(String pattern) {
		return stringRedisTemplate.keys(pattern);
	}
}



四、Redis代替Session进行缓存共享

package com.nriat.utils;

import java.util.Calendar;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.nriat.base.cache.RedisManager;
import com.nriat.base.cache.SessionManager;
import com.nriat.core.busi.model.SqlParams;
import com.nriat.core.config.Global;
import com.nriat.core.config.WechatGlobal;
import com.nriat.core.system.model.Role;
import com.nriat.core.system.model.User;

/**
 * Request 工具类,用于处理 HttpServletRequest、session等缓存工具
 * 
 * @author zxz at 20171123
 *
 */
public class CacheUtils {

	static String SESSION = "session";

	static String REDIS = "redis";

	static String cacheType = "redis";

	/**
	 * 
	 * 获取当前用户
	 * 
	 * @param session
	 * @return
	 * @throws @other:
	 *             (注意事项)
	 * 
	 * @author: pc175
	 * @date: 2018年2月7日 下午1:18:25
	 */
	public static User getCurrentUserInfo(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return (User) RedisManager.getJsonSession(Global.SESSION_USER, User.class, session.getId());
		} else {
			return (User) SessionManager.getSessionAttribute(session, Global.SESSION_USER);
		}

	}

	/**
	 * 获取用户班级编号
	 * 
	 * @param session
	 * @return
	 */
	public static String getClassId(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession("classId", session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, "classId");
		}
	}

	public static String getSchZoneCode(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession("schZoneCode", session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, "schZoneCode");
		}
	}

	public static String getClassName(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession("className", session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, "className");
		}

	}

	public static SqlParams getSqlParams(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return (SqlParams) RedisManager.getJsonSession("sqlParams", SqlParams.class, session.getId());
		} else {
			return (SqlParams) SessionManager.getSessionAttribute(session, "sqlParams");
		}
	}

	public static void setSqlParams(HttpSession session, SqlParams sqlParams) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			RedisManager.setJsonSession("sqlParams", session.getId(), sqlParams);
		} else {
			SessionManager.setSessionAttribute(session, "sqlParams", sqlParams);
		}
	}

	public static String getUserId(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession("userId", session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, "userId");
		}
	}

	public static void setUserId(HttpSession session, String userId) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			RedisManager.setSession("userId", session.getId(), userId);
		} else {
			SessionManager.setSessionAttribute(session, "userId", userId);
		}
	}

	public static void setWechatOpenid(HttpSession session, String openId) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			RedisManager.setSession(WechatGlobal.WECHAT_OPENID, session.getId(), openId);
		} else {
			SessionManager.setSessionAttribute(session, WechatGlobal.WECHAT_OPENID, openId);
		}
	}

	public static String getIsWechatLoginSuccess(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession("isWechatLoginSuccess", session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, "isWechatLoginSuccess");
		}
	}

	public static void setIsWechatLoginSuccess(HttpSession session, String isWechatLoginSuccess) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			RedisManager.setSession("isWechatLoginSuccess", session.getId(), isWechatLoginSuccess);
		} else {
			SessionManager.setSessionAttribute(session, "isWechatLoginSuccess", isWechatLoginSuccess);
		}
	}

	public static String getWechatOpenid(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession(WechatGlobal.WECHAT_OPENID, session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, WechatGlobal.WECHAT_OPENID);
		}
	}

	public static String getRoleName(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession(Global.SESSION_ROLE_NAME, session.getId(), String.class);
		} else {
			return (String) SessionManager.getSessionAttribute(session, Global.SESSION_ROLE_NAME);
		}
	}

	public static Long getRoleId(HttpSession session) {
		if (cacheType.equals(CacheUtils.REDIS)) {
			return Long.parseLong((String) RedisManager.getObjSession(Global.SESSION_ROLE_ID, session.getId()));
		} else {
			return Long.parseLong(SessionManager.getSessionAttribute(session, Global.SESSION_ROLE_ID).toString());
		}
	}

	public static String getUserName(HttpSession session) {

		if (cacheType.equals(CacheUtils.REDIS)) {
			return RedisManager.getSession(Global.SESSION_USER_NAME, session.getId(), String.class);
		} else {
			return SessionManager.getSessionAttribute(session, Global.SESSION_USER_NAME).toString();
		}
	}

	/**
	 * 保存信息到session中
	 * 
	 * @param request
	 * @param session
	 * @param user
	 * @param role
	 * @param map
	 * @param sqlParams
	 */
	public static void saveInfoToSession(HttpServletRequest request, HttpSession session, User user, Role role,
			Map<String, Object> map, SqlParams sqlParams) {

		if (sqlParams.getDateTo() == null) {
			sqlParams.setDateTo(String.valueOf(Calendar.getInstance().get(Calendar.YEAR))
					+ String.format("%02d", Calendar.getInstance().get(Calendar.MONTH)));
		}
		sqlParams.setDateFrom(sqlParams.getDateTo().substring(0, 4) + "01");
		sqlParams.setLastDateFrom(sqlParams.getDateFrom());
		int yearI = Integer.parseInt(sqlParams.getDateFrom().substring(0, 4));
		String month = sqlParams.getDateTo().substring(4, 6);
		if (sqlParams.getDateTo().substring(4, 6).equals("01")) {
			sqlParams.setLastMonth((yearI - 1) + "12");
		} else {
			sqlParams.setLastMonth((Integer.parseInt(sqlParams.getDateTo()) - 1) + "");
		}
		yearI--;
		sqlParams.setLastDateFrom(yearI + "01");
		sqlParams.setLastDateTo(yearI + sqlParams.getDateTo().substring(4, 6));

		sqlParams.setDate(CalendarUtils.getDate());
		sqlParams.setWeekEnd(CalendarUtils.getWeekEnd());
		sqlParams.setWeekStart(CalendarUtils.getWeekStart());
		sqlParams.setLastWeekDate(CalendarUtils.getLastWeekDate());
		sqlParams.setLastWeekStart(CalendarUtils.getLastWeekStart());

		sqlParams.setSchoolYears(Integer.valueOf(ApplicationProperties.getSchoolYears()));

		if (cacheType.equals(CacheUtils.REDIS)) {
			insertRedis(session, user, role, map, sqlParams);
		} else {
			insertSession(session, user, role, map, sqlParams);
		}

	}

	/**
	 * 
	 * 将用户信息插入session
	 * 
	 * @param session
	 * @param user
	 * @param role
	 * @param map
	 * @param sqlParams
	 * @throws @other:
	 *             (注意事项)
	 * 
	 * @author: pc175
	 * @date: 2018年2月6日 上午11:19:56
	 */
	private static void insertSession(HttpSession session, User user, Role role, Map<String, Object> map,
			SqlParams sqlParams) {
		if (user != null) {
			SessionManager.setSessionAttribute(session, Global.SESSION_USER_ID, user.getUserId());
			SessionManager.setSessionAttribute(session, Global.SESSION_USER_NAME, user.getUserName());
			SessionManager.setSessionAttribute(session, Global.SESSION_ROLE_ID, user.getRoleId());
			SessionManager.setSessionAttribute(session, Global.SESSION_USER, user);

			if (role != null) {
				SessionManager.setSessionAttribute(session, Global.SESSION_ROLE_NAME, role.getRoleName());
			}

		}

		if (map != null) {
			SessionManager.setSessionAttribute(session, "classId", map.get("inside_class_code"));
			SessionManager.setSessionAttribute(session, "schZoneCode", map.get("sch_zone_code"));
			SessionManager.setSessionAttribute(session, "className", map.get("class_name"));
			SessionManager.setSessionAttribute(session, "watchword", map.get("watchword"));
		}
		SessionManager.setSessionAttribute(session, "sqlParams", sqlParams);
	}

	/**
	 * 
	 * 将用户信息插入redis
	 * 
	 * @param redisManager
	 * @param user
	 * @param role
	 * @param map
	 * @param sqlParams
	 * @throws @other:
	 *             (注意事项)
	 * 
	 * @author: zxz
	 * @date: 2018年2月2日 下午2:52:20
	 */
	private static void insertRedis(HttpSession session, User user, Role role, Map<String, Object> map,
			SqlParams sqlParams) {
		String sessionId = session.getId();
		if (user != null) {
			RedisManager.setSession(Global.SESSION_USER_ID, sessionId, user.getUserId().toString());
			RedisManager.setSession(Global.SESSION_USER_NAME, sessionId, user.getUserName());
			RedisManager.setSession(Global.SESSION_ROLE_ID, sessionId, user.getRoleId().toString());
			RedisManager.setJsonSession(Global.SESSION_USER, sessionId, user);
			if (role != null) {
				RedisManager.setSession(Global.SESSION_ROLE_NAME, sessionId, role.getRoleName());
			}

		}

		if (map != null) {
			RedisManager.setSession("classId", sessionId, map.get("inside_class_code"));
			RedisManager.setSession("schZoneCode", sessionId, map.get("sch_zone_code"));
			RedisManager.setSession("className", sessionId, map.get("class_name"));

			RedisManager.setSession("watchword", sessionId, map.get("watchword"));
		}
		RedisManager.setJsonSession("sqlParams", sessionId, sqlParams);
	}

}

附:参考资料

  1. spring-data-redis 扩展实现时效设置: 缓存进行aop
  2. Redis中文网
  3. Redis 简介
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值