Spring整合redis(设置密码)完整版

时光怂恿深爱的人放手 提交于 2019-11-30 07:40:04

    博主在上个项目中使用了redis,开始使用的jedisPool连接池的方式进行整合,发现这样是不安全,调研了一下,选择了设置redis密码重新整合,总结经验如下:

   1)导入Spring-redis的jar具体如下:

        

    2)配置Spring-redis.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-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/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    <!-- 连接池配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 最大连接数 -->
        <property name="maxActive" value="30" />
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="10" />
        <!-- 每次释放连接的最大数目 -->
        <property name="numTestsPerEvictionRun" value="1024" />
        <!-- 释放连接的扫描间隔(毫秒) -->
        <property name="timeBetweenEvictionRunsMillis" value="30000" />
        <!-- 连接最小空闲时间 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
        <property name="softMinEvictableIdleTimeMillis" value="10000" />
        <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
        <property name="MaxWait" value="15000" />
        <!-- 在获取连接的时候检查有效性, 默认false -->
        <property name="testOnBorrow" value="true" />
        <!-- 在空闲时检查有效性, 默认false -->
        <property name="testWhileIdle" value="true" />
    </bean>

    <!-- redis服务器中心 -->  
   <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >  
         <property name="poolConfig" ref="poolConfig" />    

<!-- 端口号-->
         <property name="port" value="6379" />  

<!-- host-->
         <property name="hostName" value="172.16.30.73" />  

<!-- redis密码-->
         <property name="password" value="123456" />  
         <property name="usePool" value="true"></property>
         <property name="timeout" value="20000" ></property>  
   </bean >  
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >  
         <property name="connectionFactory" ref="connectionFactory" />  
         <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 >
 <!-- 将redisTemplate注入redisSession -->
  <bean id="redisSession" class="com.custle.webutil.RedisSession">
  		<property name="redisTemplate" ref="redisTemplate"/>
  </bean>
  
</beans>

        3)配置Redis会话工具类

需要声明一点,Static变量使用Spring注入,Static变量的set方法不能加上static修饰。

package com.custle.webutil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.custle.vo.info.UserInfoVO;

public class RedisSession {
	private static ApplicationContext context;
	private static RedisTemplate<Serializable, Object> redisTemplate;
	private static int validTime =  60*30; //单位秒 

	/*static {
		// 加载配置文件
		context = new ClassPathXmlApplicationContext("applicationContext-redis.xml");
		
		redisTemplate = (RedisTemplate<Serializable, Object>) context.getBean("redisTemplate");
	}*/
	public  RedisTemplate<Serializable, Object> getRedisTemplate() {
		return redisTemplate;
	}
       //spring设置注入redisTemplate
	public  void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
		RedisSession.redisTemplate = redisTemplate;
	}
	
	public static void setAttribute(String token, String name, Serializable value) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		Object obj = operations.get(token);
		Map<String, Serializable> session;
		if(obj == null){
			session = new HashMap<String, Serializable>();
		}else{
			session = (Map<String, Serializable>) obj;
		}
		session.put(name, value);
		operations.set(token, session);
		redisTemplate.expire(token, validTime, TimeUnit.SECONDS);
	
		//返回连接
	}
	
	public static Object getAttribute(String token, String name) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		Object obj = operations.get(token);
		Map<String, Serializable> session = (Map<String, Serializable>) obj;
		if (null != session) {
			//若存在,延长有效期
			redisTemplate.expire(token, validTime, TimeUnit.SECONDS);
			return session.get(name);
		}
		return null;
	}
	
	/**
	 * 一次取多个值
	 * @param token
	 * @param names
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static Map<String,Serializable> getMap(String token) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		Object obj = operations.get(token);
		Map<String, Serializable> session = (Map<String, Serializable>) obj;
		if (null != session) {
			//若存在,延长有效期
			redisTemplate.expire(token, validTime, TimeUnit.SECONDS);
			return session;
		}
		return null;
	}
	
	/**
	 * 批量存
	 * @param token
	 * @param name
	 * @param value
	 * @throws UnsupportedEncodingException
	 */
	public static void setMap(String token,HashMap<String, Serializable> map) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		Object obj = operations.get(token);
		Map<String, Serializable> session;
		if(obj == null){
			session = new HashMap<String, Serializable>();
		}else{
			session = (Map<String, Serializable>) obj;
		}
		session.putAll(map);
		operations.set(token, session);
		redisTemplate.expire(token, validTime, TimeUnit.SECONDS);
	}

	public static void logout(String token) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		// 如果存在这个key 则删除此条数据
		if (redisTemplate.hasKey(token)) {
			redisTemplate.delete(token);
		}
	}
	

	public static void setAttribute(String token, String name, Serializable value, int timeOut) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		Object obj = operations.get(token);
		Map<String, Serializable> session;
		if(obj == null){
			session = new HashMap<String, Serializable>();
		}else{
			session = (Map<String, Serializable>) obj;
		}
		session.put(name, value);
		// 保存到redis
		operations.set(token, session);
		redisTemplate.expire(token, timeOut, TimeUnit.SECONDS);
		//redisTemplate.expire(token, validTime, TimeUnit.SECONDS);
		//返回连接
	}
	
	
	/**
	 * 设置普通的redis缓存(不带session)
	 * @param key
	 * @param value
	 * @param timeOut
	 * @throws UnsupportedEncodingException
	 */
	public static void setCommonAttribute(String key, Object value, int timeOut) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		// 保存到redis
		operations.set(key, value);
		redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
		//返回连接
	}
	
	/**
	 * 设置存入Oject的redis缓存(不带session)
	 * @param key
	 * @param value 
	 * @param timeOut
	 * @throws UnsupportedEncodingException
	 */
	public static void setObjectAttribute(String key, Object value, int timeOut) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		// 保存到redis
		operations.set(key, value);
		redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
		//返回连接
	}
	
	public static Object getObjectAttribute(String key) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		// 保存到redis
		return operations.get(key);
		//返回连接
	}
	
	
	public static Object getCommonAttribute(String key) throws UnsupportedEncodingException {
		ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue(); 
		// 保存到redis
		return operations.get(key);
		//返回连接
	}
	
    /** 
     * 序列化 list 集合 
     *  
     * @param list 
     * @return 
     */  
    public static byte[] serializeList(List<?> list) {  
  
        ObjectOutputStream oos = null;  
        ByteArrayOutputStream baos = null;  
        byte[] bytes = null;  
        try {  
            baos = new ByteArrayOutputStream();  
            oos = new ObjectOutputStream(baos);  
            for (Object obj : list) {  
                oos.writeObject(obj);  
            }  
            bytes = baos.toByteArray();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            close(oos);  
            close(baos);  
        }  
        return bytes;  
    }  
  
    /** 
     * 反序列化 list 集合 
     *  
     * @param lb 
     * @return 
     */  
    public static List<?> unserializeList(byte[] bytes) {  
        if (bytes == null) {  
            return null;  
        }  
  
        List<Object> list = new ArrayList<Object>();  
        ByteArrayInputStream bais = null;  
        ObjectInputStream ois = null;  
        try {  
            // 反序列化  
            bais = new ByteArrayInputStream(bytes);  
            ois = new ObjectInputStream(bais);  
            while (bais.available() > 0) {  
                Object obj = (Object) ois.readObject();  
                if (obj == null) {  
                    break;  
                }  
                list.add(obj);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            close(bais);  
            close(ois);  
        }  
        return list;  
    }  
  
    /** 
     * 关闭io流对象 
     *  
     * @param closeable 
     */  
    public static void close(Closeable closeable) {  
        if (closeable != null) {  
            try {  
                closeable.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    }
    
    
}

    

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!