1.原料
apache-maven 3.9.X
Oracle-jdk 1.8.X
Eclipse || IDEA
MongoDB 3.6.X
2.配置
maven -- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
启动器和测试控制器
import javax.servlet.http.HttpSession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableMongoHttpSession
@RestController
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/set")
public String setSession(HttpSession session, String sss) {
session.setAttribute("hello", sss);
return "ok!";
}
@RequestMapping("/get")
public String getSession(HttpSession session) {
return session.getAttribute("hello").toString();
}
}
application.properties
### 节点1
spring.session.store-type=MongoDB
spring.session.jdbc.table-name=SESSIONS
server.servlet.session.timeout=30
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=spring-session
server.port=8080
### 节点2
spring.session.store-type=MongoDB
spring.session.jdbc.table-name=SESSIONS
server.servlet.session.timeout=30
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=spring-session
server.port=8081
3.启动和验证
1. 分别启动节点 1 和节点 2
2. 验证
选取任意节点进行设值:
>### ![imagepng](http://blog.lesswork.cn/solo/upload/c5f5eaab2c634cfba4dfb05be202175d_image.png)
查看:
![imagepng](http://blog.lesswork.cn/solo/upload/c009ab319a194e4aa0839f05b7749171_image.png)
4.注意事项
@EnableMongoHttpSession
此注解为开启 MongoDB 存储 session 的专用注解,千万不要搞混
mongo 依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
此依赖必需,否则项目无法启动
YouY Blog —— 专心做你的烂笔头。访问主页
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于