代码的整体结构
- RedisSessionConfig.java
package com.cc.springbootredissession.config;import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
}
- SessionsController
package com.cc.springbootredissession;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/sessions")
public class SessionsController {//映射到http://localhost:8093/sessions/set//设置@GetMapping("/set")public Map<String, Object> setSession(HttpServletRequest request) {Map<String, Object> map = new HashMap<>();request.getSession().setAttribute("request Url", request.getRequestURL());map.put("request Url", request.getRequestURL());return map;}//映射到http://localhost:8093/sessions/list//取值@GetMapping(value = "/list")public Object sessions (HttpServletRequest request){Map<String, Object> map = new HashMap<>();map.put("sessionId", request.getSession().getId());map.put("message", request.getSession().getAttribute("request Url"));return map;}
}
- application.properties
spring.redis.database=0
# server host1 单机使用,对应服务器ip
spring.redis.host=192.168.133.130
# server password 密码,如果没有设置可不配
#spring.redis.password=
#connection port 单机使用,对应端口号
spring.redis.port=10190
# pool settings ...池配置
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
- 使用命令curl -i http://localhost:8093/sessions/set进行链接的设置
- 模拟多节点,需要将文件打包,使用命令mvn package
- 使用命令java -jar springboot-redis-session-0.0.1-SNAPSHOT.jar --server.port=8000,模拟8000端口
- 使用命令java -jar springboot-redis-session-0.0.1-SNAPSHOT.jar --server.port=8001,模拟8001端口
- 在浏览器输入http://localhost:8000/sessions/list,查看session的id
- 在浏览器输入http://localhost:8001/sessions/list,查看session的id
- 他们的session是一样的,从而实现了session的共享