【缓存】Redis基础使用详解及配置

直接上代码,

applicationContext.xml 中的配置

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
		<property name="locations">  
			<list>  
                <value>classpath:dbconfig.properties</value>
                <value>classpath:redis.properties</value>
            </list>  
        </property>  
	</bean>
    
    <import resource="spring-redis.xml"/>


	<!-- ================ Shiro start ================ -->
    <!--shiro-redis redisCacheManager-->
    <bean id="redisCacheManager" class="org.crazycake.shiro.RedisCacheManager">
        <property name="expire" value="10800"/>
        <property name="keyPrefix" value="shiro_redis_session:"/>
        <property name="redisManager" ref="redisClient"/>
    </bean>

	<!-- 項目自定义的Realm -->
	<bean id="shiroRealm" class="com.douples.framework.interceptor.shiro.ShiroRealm" >
		<property name="cacheManager" ref="redisCacheManager"/>
	</bean>

	<bean id="redisSessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO" />
     

      
	<!--sessionManager-->
	<bean id="sessionManager" class="com.douples.common.util.RedisWebSessionManager">
		<property name="sessionDAO" ref="redisSessionDAO"/>
		<property name="globalSessionTimeout" value="7200000"/>
		<!-- <property name="sessionValidationInterval" value="2000"/> -->
		<!-- <property name="sessionValidationSchedulerEnabled" value="true"/> -->
		<property name="sessionIdCookie" ref="simpleCookie"/>
		<property name="sessionIdCookieEnabled" value="true"/>
	</bean>

	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="shiroRealm" />
		<property name="cacheManager" ref="redisCacheManager"/>
		<property name="sessionManager" ref="sessionManager"/>
	</bean>

RedisUtil.java工具类

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Redis 操作工具类
 *
 */
public class RedisUtil {

    private static Logger _log = LoggerFactory.getLogger(RedisUtil.class);

    protected static ReentrantLock lockPool = new ReentrantLock();
    protected static ReentrantLock lockJedis = new ReentrantLock();

    // Redis 服务器 IP
    private static String IP = PropertiesFileUtil.getInstance("redis").get("redis.host");

    // Redis 的端口号
    private static int PORT = PropertiesFileUtil.getInstance("redis").getInt("redis.port");

    // 访问密码
    private static String PASSWORD = PropertiesFileUtil.getInstance("redis").get("redis.password");

    // 可用连接实例的最大数目,默认值为 8;
    // 如果赋值为-1,则表示不限制;
    // 如果 pool 已经分配了 maxActive 个 jedis 实例,则此时 pool 的状态为 exhausted (耗尽)。
    private static int MAX_ACTIVE = PropertiesFileUtil.getInstance("redis").getInt("redis.max_active");

    // 控制一个 pool 最多有多少个状态为 idle (空闲的)的 jedis 实例,默认值也是 8。
    private static int MAX_IDLE = PropertiesFileUtil.getInstance("redis").getInt("redis.max_idle");

    // 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出 JedisConnectionException;
    private static int MAX_WAIT = PropertiesFileUtil.getInstance("redis").getInt("redis.max_wait");

    // 超时时间
    private static int TIMEOUT = PropertiesFileUtil.getInstance("redis").getInt("redis.timeout");

    // 在 borrow 一个 jedis 实例时,是否提前进行 validate 操作;如果为 true,则得到的 jedis 实例均是可用的;
    private static boolean TEST_ON_BORROW = false;

    private static JedisPool jedisPool = null;

    /**
     * redis 过期时间,以秒为单位
     */
    public final static int EXRP_HOUR = 60 * 60;            //一小时
    public final static int EXRP_DAY = 60 * 60 * 24;        //一天
    public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月

    /**
     * 初始化 Redis 连接池
     */
    private static void initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
        } catch (Exception e) {
            _log.error("创建 JedisPool 错误: " + e);
        }
    }

    /**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (null == jedisPool) {
            initialPool();
        }
    }

    /**
     * 同步获取 Jedis 实例
     * @return Jedis
     */
    public synchronized static Jedis getJedis() {
        poolInit();
        Jedis jedis = null;
        try {
            if (null != jedisPool) {
                jedis = jedisPool.getResource();
                try {
                    jedis.auth(PASSWORD);
                } catch (Exception e) {
                    _log.error("Redis 密码验证失败 : " + e);
                }
            }
        } catch (Exception e) {
            _log.error("Get jedis error : " + e);
        }
        return jedis;
    }

    /**
     * 设置 String
     * @param key
     * @param value
     */
    public synchronized static void set(String key, String value) {
        try {
            value = StringUtils.isBlank(value) ? "" : value;
            Jedis jedis = getJedis();
            jedis.set(key, value);
            jedis.close();
        } catch (Exception e) {
            _log.error("Set key error : " + e);
        }
    }

    /**
     * 设置 byte[]
     * @param key
     * @param value
     */
    public synchronized static void set(byte[] key, byte[] value) {
        try {
            Jedis jedis = getJedis();
            jedis.set(key, value);
            jedis.close();
        } catch (Exception e) {
            _log.error("Set key error : " + e);
        }
    }

    /**
     * 设置 String 过期时间
     * @param key
     * @param value
     * @param seconds 以秒为单位
     */
    public synchronized static void set(String key, String value, int seconds) {
        try {
            value = StringUtils.isBlank(value) ? "" : value;
            Jedis jedis = getJedis();
            jedis.setex(key, seconds, value);
            jedis.close();
        } catch (Exception e) {
            _log.error("Set keyex error : " + e);
        }
    }

    /**
     * 设置 byte[] 过期时间
     * @param key
     * @param value
     * @param seconds 以秒为单位
     */
    public synchronized static void set(byte[] key, byte[] value, int seconds) {
        try {
            Jedis jedis = getJedis();
            jedis.set(key, value);
            jedis.expire(key, seconds);
            jedis.close();
        } catch (Exception e) {
            _log.error("Set key error : " + e);
        }
    }

    /**
     * 获取 String 值
     * @param key
     * @return value
     */
    public synchronized static String get(String key) {
        Jedis jedis = getJedis();
        if (null == jedis) {
            return null;
        }
        String value = jedis.get(key);
        jedis.close();
        return value;
    }

    /**
     * 获取byte[]值
     * @param key
     * @return value
     */
    public synchronized static byte[] get(byte[] key) {
        Jedis jedis = getJedis();
        if (null == jedis) {
            return null;
        }
        byte[] value = jedis.get(key);
        jedis.close();
        return value;
    }

    /**
     * 删除值
     * @param key
     */
    public synchronized static void remove(String key) {
        try {
            Jedis jedis = getJedis();
            jedis.del(key);
            jedis.close();
        } catch (Exception e) {
            _log.error("Remove keyex error : " + e);
        }
    }

    /**
     * 删除值
     * @param key
     */
    public synchronized static void remove(byte[] key) {
        try {
            Jedis jedis = getJedis();
            jedis.del(key);
            jedis.close();
        } catch (Exception e) {
            _log.error("Remove keyex error : " + e);
        }
    }

    /**
     * lpush
     * @param key
     * @param key
     */
    public synchronized static void lpush(String key, String... strings) {
        try {
            Jedis jedis = RedisUtil.getJedis();
            jedis.lpush(key, strings);
            jedis.close();
        } catch (Exception e) {
            _log.error("lpush error : " + e);
        }
    }

    /**
     * lrem
     * @param key
     * @param count
     * @param value
     */
    public synchronized static void lrem(String key, long count, String value) {
        try {
            Jedis jedis = RedisUtil.getJedis();
            jedis.lrem(key, count, value);
            jedis.close();
        } catch (Exception e) {
            _log.error("lpush error : " + e);
        }
    }

    /**
     * sadd
     * @param key
     * @param value
     * @param seconds
     */
    public synchronized static void sadd(String key, String value, int seconds) {
        try {
            Jedis jedis = RedisUtil.getJedis();
            jedis.sadd(key, value);
            jedis.expire(key, seconds);
            jedis.close();
        } catch (Exception e) {
            _log.error("sadd error : " + e);
        }
    }

    /**
     * incr
     * @param key
     * @return value
     */
    public synchronized static Long incr(String key) {
        Jedis jedis = getJedis();
        if (null == jedis) {
            return null;
        }
        long value = jedis.incr(key);
        jedis.close();
        return value;
    }

    /**
     * decr
     * @param key
     * @return value
     */
    public synchronized static Long decr(String key) {
        Jedis jedis = getJedis();
        if (null == jedis) {
            return null;
        }
        long value = jedis.decr(key);
        jedis.close();
        return value;
    }

}

Controller中进行调用

       public static final String LOGIN_TELEPHONE = "ACCOUNT:LOGINED:";

        // 把同个用户前面登录人员的 session 清理掉
		String currSessionID = RedisUtil.get(LOGIN_TELEPHONE + pd.get("mobile"));
		if (currSessionID != null && !Objects.equals("", currSessionID)) {
		    RedisUtil.remove(currSessionID); // 把该 session 直接去掉
	}
		// 记录新的 session
	RedisUtil.set(LOGIN_TELEPHONE + pd.get("mobile"), SHIRO_SESSION_PREFIX + session.getId());

	Subject subject = SecurityUtils.getSubject();

	UsernamePasswordToken token = new UsernamePasswordToken(pd.getString("USER_NAME"), passWord);
			

猜你喜欢

转载自blog.csdn.net/zxwu_1993/article/details/87917944