springboot中session如何共享

springboot+Redis 解决session共享问题

分布式项目现在遍地都是了,但同时也带来一个问题,那就是session共享的问题,将项目分布了以后,不可能每一个都登录一遍,顾客体验极其不好,那么只有一个办法了,session共享,解决这个有两个办法,一个是基于Redis Nosql的方案,另一个是OAuth-token这类的办法解决,可能还有其他的,希望留言,非常感谢。

本篇主要讲解redis 的方案

A> 构建两个springboot-web项目,端口分别定位8080和9080
在application.properties中定义端口
就是一个简单的端口描述
第二个端口描述
B>若要开启Redis 的session共享,需要在启动类中加入注解 @EnableRedisHttpSession
加入注解

注解是包含在这个依赖中的

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
		</dependency>

C>启动Redis 加入配置端口ip
我这里是用的本地的windows的Redis版本
redis的启动页面

spring.redis.host=localhost
spring.redis.port=6379

两个application.properties都配置好redis的ip和端口之后指向同一个redis 这样两个tomcate就实现了session共享

下面我们来测试一下

@Controller
public class SessionController {

    @RequestMapping("/getsession")
    @ResponseBody
    public Map<Object, Object> getSession(HttpServletRequest req) {
        req.getSession().setAttribute(req.getRequestURI(), req.getRequestedSessionId());
        req.getSession().setAttribute("key", "port = 9080");
        Map<Object, Object> map = new HashMap<>();
        map.put(req.getRequestURI(), req.getRequestedSessionId());
        map.put(req.getSession().getAttribute("key"), req.getRequestedSessionId());
        return map;
    }
}

在两个项目中分别加入此controller
启动可能会报错
…RedisConnectionFactory’ that could not be found.
原因是创建连接redis的工厂类找不到,少加了依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

再启动应该就不报错了
分别在浏览器中访问
http://localhost:8080/getsession
http://localhost:9080/getsession
分别得到
在这里插入图片描述
在这里插入图片描述
得到两个端口不同但是得到的sessionId 是相同的,由此证明两个工程已经共享了一个session,即访问这个登录以后再去访问另一个工程便不需要再次登录了。

おすすめ

転載: blog.csdn.net/weixin_41086086/article/details/88570650