一. SpringBoot中实现Session共享
1. 创建web项目
我们按照之前的经验,创建一个web程序,并将之改造成Spring Boot项目,具体过程略。
2.添加依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-core</artifactId> </dependency>
3.创建application.yml文件
server: port: 8080 #配置redis spring: redis: host: 127.0.0.1 port: 6379 #password: 123456 jedis: pool: max-idle: 8 min-idle: 0 max-active: 8 #max-wait: 60000 #timeout: 3000 #超时一定要大于0 session: #设置session存储类型 store-type: redis
这里可以设置多种session的store-type:
我们这里选择利用redis来对session进行集中存储,实现session共享。
4.创建Session配置类
package com.yyg.boot.config; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * @Author 一一哥Sun * @Date Created in 2020/4/28 * @Description 开启Redis Http Session */ @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600) public class RedisHttpSessionConfiguration { }
在这里添加@EnableRedisHttpSession注解,可以通过maxInactiveIntervalInSeconds属性设置Session的过期时间。
5.创建一个Controller接口方法
该接口方法当用户不存在时提示“用户不存在”,否则会提示“用户存在”。
package com.yyg.boot.web; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.Reque<a style="color:transparent">本文来源gao($daima.com搞@代@#码$网</a>stParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Author 一一哥Sun * @Date Created in 2020/4/28 * @Description Description */ @Slf4j @RestController public class SessionController { @RequestMapping("/session") public Object springSession(@RequestParam("username") String username, HttpServletRequest request, HttpSession session) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { log.warn(cookie.getName() + "=" + cookie.getValue()); } } Object value = session.getAttribute("username"); if (value == null) { log.warn("用户不存在"); //保存session session.setAttribute("username", "{username: '" + username + "', age: 30}"); } else { log.warn("用户存在"); } return "username=" + value; } }
6.创建入口类
package com.yyg.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @Author 一一哥Sun * @Date Created in 2020/4/28 * @Description Description */ @SpringBootApplication public class SpringSessionApplication { public static void main(String[] args){ springapplication.run - 这个网站可出售。 - 最佳的springapplication 来源和相关信息。(SpringSessionApplication.class,args); } }