项目中需要两个不同的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拿一次用户信息,就能得到一个项目登录,跳转另一个项目就自动登录的效果了。

redis做session会话共享的更多相关文章

  1. Tomcat通过自带的Cluster方式实现Session会话共享环境操作记录

    一般来说,在多个tomcat集群业务中,session会话共享是必须的需求,不然前端nginx转发过来的请求不知道之前请求在哪台tomcat节点上,从而就找不到session以至于最终导致请求失败.要 ...

  2. nginx+redis实现session的共享

    上一篇我们介绍了nginx实现的负载均衡和动静分离,可看这边. 我们在文章的末尾说到,负载均衡需要面临的一个问题是内存数据的同步.例如:我有A,B两台服务器做了负载均衡,当我在A服务器上执行了登录并且 ...

  3. tomcat用redis做session共享

    在context.xml添加以下配置: <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerVa ...

  4. 展开被 SpringBoot 玩的日子 《 四 》 Session 会话共享

    共享Session-spring-session-data-redis 分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一. Spring Session官方说 ...

  5. Django Redis存储session会话

    通常redis都是用来保存session.短信验证码.图片验证码等数据. 在django上使用redis,先要安装一个包: pip install django-redis==4.8.0(我用的dja ...

  6. nginx负载均衡搭建phpmyadmin加入redis了解session会话原理

    myphpadmin项目理解cookie和session 当我们平时上网的时候,在刷新之后或者退出浏览器再次打开浏览器不需要登陆网页了,这就是利用了cookie和session: 环境配置 hostn ...

  7. Centos7 安装redis 并新建springboot工程使用Redis 做session

    Redis 安装 就是解压运行,根据自己的爱好,放到文件夹中 tar -zxvf redis-5.0.4.tar.gz yum install gcc cd redis-5.0.4 make MALL ...

  8. php session 保存到redis 实现session的共享

    1.redis安装肯定都会了,就不介绍了. 2.核心代码

  9. memcached session会话共享

    1 安装依赖包yum install libevent livevent-devel nc -y 2 yum 安装memcachedyum install -y memcached 3 启动memec ...

随机推荐

  1. ElasticHD Windows环境下安装

    ElasticHD Linux环境下安装教程        ElasticHD windows环境下安装教程   习惯了T-SQL 查询,Elasticsearch的DSL查询语法简直就是反人类呀,一 ...

  2. 复习 LIS nlogn

    参考:https://www.cnblogs.com/wxjor/p/5524447.html 最长下降只要把符号都倒过来就行 在栈中二分找第一个比当前值小的替换就行

  3. Mining Station on the Sea HDU - 2448(费用流 || 最短路 && hc)

    Mining Station on the Sea Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Jav ...

  4. 【CF633D】Fibonacci-ish

    题目描述 小y最近迷上了fibonacci数列,他定义了一种数列叫类fibonacci数列: 1.这个数列包含至少\(2\)个元素 2.\(f_0\)和\(f_1\)是任意选取的 3.\(f_{n+2 ...

  5. studio 连不上远程仓库的各种原因分析

    Unable to open the project 1.远程服务器挂了2.网络断了3.登录远程服务器的账号.密码错了4.远程仓库的url地址,被本地的hosts文件重定向了5.要下载远程仓库的某个j ...

  6. 使用 JavaScript, HTML 和 CSS 构建跨平台的桌面应用

    https://electronjs.org/ —— 官网 https://github.com/electron/electron-api-demos/releases —— 下载demo 下载安装 ...

  7. 【AtCoder - 2300】Snuke Line(树状数组)

    BUPT2017 wintertraining(15) #9A 题意 有n个纪念品,购买区间是\([l_i,r_i]\).求每i(1-m)站停一次,可以买到多少纪念品. 题解 每隔d站停一次的列车,一 ...

  8. IDEA+Springboot+JRebel热部署实现

    步骤一:在IDEA中安装JRebel插件(File->settings->plugins->search in repositories),如下图 步骤二:安装完成之后,重启idea ...

  9. 用keras实现基本的回归问题

    数据集介绍 共有506个样本,拆分为404个训练样本和102个测试样本 该数据集包含 13 个不同的特征: 人均犯罪率. 占地面积超过 25000 平方英尺的住宅用地所占的比例. 非零售商业用地所占的 ...

  10. [FJOI2016]神秘数(脑洞+可持久化)

    题目描述 一个可重复数字集合S的神秘数定义为最小的不能被S的子集的和表示的正整数.例如S={1,1,1,4,13}, 1 = 1 2 = 1+1 3 = 1+1+1 4 = 4 5 = 4+1 6 = ...