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

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

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

        212225_iesv_3697923.png

    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();  
            }  
        }  
    }
    
    
}

    

转载于:https://my.oschina.net/u/3697923/blog/1558338

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring整合Redis可以通过以下步骤进行操作。首先,需要在pom.xml文件中添加Redis的依赖项,如下所示:\[1\] ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,在application.properties文件中配置Redis的相关属性,包括数据库选择、IP地址和端口号等,如下所示:\[1\] ```properties # RedisProperties # 选择第12个数据库 spring.redis.database=11 # 配置IP地址 spring.redis.host=localhost # 配置端口号 spring.redis.port=6379 ``` 然后,创建一个RedisConfig类,用于配置Redis连接池和RedisTemplate等相关配置。在该类中,可以设置最大连接数、最大空闲连接数、连接超时时间等属性,如下所示:\[1\] 最后,可以在需要使用Redis的地方调用Redis相关的service进行操作。可以根据需要使用RedisTemplate或者Jedis等工具类进行操作,如下所示:\[2\] 以上是在Spring整合Redis的基本步骤和配置。通过这些配置,可以方便地在Spring项目中使用Redis进行数据缓存和存储操作。\[1\]\[2\] #### 引用[.reference_title] - *1* [Spring整合Redis](https://blog.csdn.net/weixin_48632843/article/details/124112102)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringRedis整合详解](https://blog.csdn.net/feiyangtianyao/article/details/87619128)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值