zoukankan      html  css  js  c++  java
  • Redis-Session会话共享

    项目中需要两个不同的web项目互相访问,用户对象为同一个User。决定用Redis来存储用户对象信息。。。ok,环境搭建开始:

    1.pom.xml引入Redis依赖的jar:

    <!-- jedis -->
    	<dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.6.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.7.3</version>
            </dependency>
    

    2.新建 spring-redis.xml :

     <!-- 配置JedisPoolConfig实例 -->  
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
            <property name="maxIdle" value="${redis.maxIdle}" />  
            <property name="maxTotal" value="${redis.maxActive}" />  
            <property name="maxWaitMillis" value="${redis.maxWait}" />  
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
        </bean>  
          
        <!-- 配置JedisConnectionFactory -->  
        <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
            <property name="hostName" value="${redis.host}"/>  
            <property name="port" value="${redis.port}"/>  
            <!-- <property name="password" value="${redis.pass}"/> -->
            <property name="database" value="${redis.dbIndex}"/>  
            <property name="poolConfig" ref="poolConfig"/>  
        </bean>  
          
        <!-- 配置RedisTemplate -->  
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
            <property name="connectionFactory" ref="jedisConnectionFactory"/>  
        </bean>  
    

    3.新建 redis.properties:

    redis.host=192.168.152.129(redis部署所在的服务器地址)
    redis.port=6379   
    redis.maxIdle=100
    redis.maxActive=300
    redis.maxWait=1000
    redis.testOnBorrow=true
    redis.dbIndex=0  
    

    4.在Spring总的配置文件中将spring-redis.xml include进去(用过spring的人都知道怎么做吧。。。)

    5.新建Redis操作工具类(里面的方法可以自己扩充):

    package com.odao.utils.redis;
    
    import java.io.UnsupportedEncodingException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    /**
     * 
     * @author wangfj
     *
     */
    @Component
    public class RedisUtils {
         private static String redisCode = "utf-8";
    	 
         @Autowired
         private RedisTemplate redisTemplate;
    	 
        /**
         * @param key
         */
        public long del(final String... keys) {
            return (Long) redisTemplate.execute(new RedisCallback() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    long result = 0;
                    for (int i = 0; i < keys.length; i++) {
                        result = connection.del(keys[i].getBytes());
                    }
                    return result;
                }
            });
        }
    
    	    /**
    	     * @param key
    	     * @param value
    	     * @param liveTime
    	     */
    	    public void set(final byte[] key, final byte[] value, final long liveTime) {
    	        redisTemplate.execute(new RedisCallback() {
    	            public Long doInRedis(RedisConnection connection) throws DataAccessException {
    	                connection.set(key, value);
    	                if (liveTime > 0) {
    	                    connection.expire(key, liveTime);
    	                }
    	                return 1L;
    	            }
    	        });
    	    }
    
    	    /**
    	     * @param key
    	     * @param value
    	     * @param liveTime
    	     */
    	    public void set(String key, String value, long liveTime) {
    	        this.set(key.getBytes(), value.getBytes(), liveTime);
    	    }
    
    	    /**
    	     * @param key
    	     * @param value
    	     */
    	    public void set(String key, String value) {
    	        this.set(key, value, 0L);
    	    }
    
    	    /**
    	     * @param key
    	     * @param value
    	     */
    	    public void set(byte[] key, byte[] value) {
    	        this.set(key, value, 0L);
    	    }
    
    	    /**
    	     * @param key
    	     * @return
    	     */
    	    public String get(final String key) {
    	        return (String) redisTemplate.execute(new RedisCallback() {
    	            public String doInRedis(RedisConnection connection) throws DataAccessException {
    	                try {
    	                    return new String(connection.get(key.getBytes()), redisCode);
    	                } catch (UnsupportedEncodingException e) {
    	                    e.printStackTrace();
    	                }
    	                return "";
    	            }
    	        });
    	    }
    
    	    /**
    	     * @param key
    	     * @return
    	     */
    	    public boolean exists(final String key) {
    	        return (Boolean) redisTemplate.execute(new RedisCallback() {
    	            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
    	                return connection.exists(key.getBytes());
    	            }
    	        });
    	    }
    
    	    /**
    	     * @return
    	     */
    	    public String flushDB() {
    	        return (String) redisTemplate.execute(new RedisCallback() {
    	            public String doInRedis(RedisConnection connection) throws DataAccessException {
    	                connection.flushDb();
    	                return "ok";
    	            }
    	        });
    	    }
    
    	    /**
    	     * @return
    	     */
    	    public long dbSize() {
    	        return (Long) redisTemplate.execute(new RedisCallback() {
    	            public Long doInRedis(RedisConnection connection) throws DataAccessException {
    	                return connection.dbSize();
    	            }
    	        });
    	    }
    
    	    /**
    	     * @return
    	     */
    	    public String ping() {
    	        return (String) redisTemplate.execute(new RedisCallback() {
    	            public String doInRedis(RedisConnection connection) throws DataAccessException {
    	                return connection.ping();
    	            }
    	        });
    	    }
    
    
    	   
    }
    

     6.新建对象序列化工具类:

    package com.odao.utils.common.config;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    /**
     * 
     * @author wangfj
     *
     */
    public class SerializeUtil {
    	//序列化对象
    	public static byte[] serialize(Object object) {
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;
            try {
                 baos = new ByteArrayOutputStream();
                 oos = new ObjectOutputStream(baos);
                 oos.writeObject(object);
                 byte[] bytes = baos.toByteArray();
                 return bytes;
            }catch (Exception e) {
            	e.printStackTrace();
            }
            return null;
       }
    	
       //反序列化对象
       public static Object unserialize( byte[] bytes) {
            ByteArrayInputStream bais = null;
            try {
                 bais = new ByteArrayInputStream(bytes);
                 ObjectInputStream ois = new ObjectInputStream(bais);
                  return ois.readObject();
            } catch (Exception e) {
            	e.printStackTrace();
            }
            return null;
       }
       
    }
    

     7.登录时,将用户对象存到Redis(做测试,用的超时时间为1分钟):

    redisUtils.set("userInfo".getBytes(), SerializeUtil.serialize(user),60);
    

     8.做了一个测试类:

    public static void main(String[] args){
            Jedis jedis = new Jedis("192.168.152.129",6379);
            byte[] value = jedis.get("userInfo".getBytes());
            if(value != null){
                Object object = SerializeUtil.unserialize(value);
                if(object != null){
                    User user = (User)object;
                    System.out.println(user.getUserName()+"=="+user.getPassword());
                }
            }
        }

     运行结果:

    wangfj==1c29b046d2723c5939fcaca89da2857b
    

    总结:既然用户对象已经存储到了Redis中,那么我们只需要在每个项目中加一个跳转另一个系统的链接(登录链接)

            将Redis中的这个用户的key传过去,然后再被跳转的项目中

            通过Redis拿一次用户信息,就能得到一个项目登录,跳转另一个项目就自动登录的效果了。

  • 相关阅读:
    jquery开发之第一个程序
    结构体大小求值
    SpringMVC 理论与有用技术(一) 简单、有用、易懂的几个实例
    北极的夜空
    Assignment (HDU 2853 最大权匹配KM)
    让linux history命令显示命令的运行时间、在哪个机器运行的这个命令
    [0day]基础工具学习
    Matlab adaptive quadrature
    计蒜之道 初赛 第三场 题解 Manacher o(n)求最长公共回文串 线段树
    辛星跟您解析在CSS面包屑中三角形的定位问题
  • 原文地址:https://www.cnblogs.com/wangfajun/p/5776745.html
Copyright © 2011-2022 走看看