MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs 菜单
Docs 主页
/ /

开始使用 Spring Session MongoDB

在本教程中,您可以学习;了解如何在 Spring Boot应用程序中使用 Spring Session MongoDB 。 Spring Session MongoDB是由MongoDB维护的开源集成,它使应用程序能够在MongoDB中存储 Spring Session 数据。

按照本教程将示例Spring Boot应用程序连接到MongoDB Atlas部署以进行会话存储。

提示

本教程修改在 Spring Data Framework 集成教程中创建的 Spring Boot应用程序。本页上的步骤展示了如何更新该应用程序以使用 Spring Session MongoDB。

完成以下步骤,设立Spring Boot应用程序,并在开发环境中安装 Spring Session MongoDB 。

1

在开始本教程之前,请确保安装并设立以下先决条件:

注意

本教程介绍如何在 IDE 中使用 Maven 安装 Spring Session MongoDB 。如果您不使用 IDE,请访问 构建 Maven 以学习;了解如何设立项目。

2

完成 Spring Data Framework 集成教程以创建新的 Spring Boot应用程序。您还可以通过访问 GitHub 上的 SpringDataMongoBulkInsert存储库来查看和克隆应用程序代码。

完成本先决条件教程后,您将拥有一个新应用程序,它使用 Spring Data MongoDB对MongoDB集合执行批量插入操作。

3

pom.xml文件中,将 spring-boot-starter-parent 依赖项替换为以下代码:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.0</version>
<relativePath/> <!-- Lookup parent from repository -->
</parent>

这可确保您的应用程序使用与 Spring 会话 4.0 兼容的 Spring Boot 4.0。

然后,将以下依赖项添加到文件的依赖项列表中以使用 Spring Session MongoDB:

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-spring-session</artifactId>
<version>4.0.0-rc0</version>
</dependency>

配置依赖项后,运行依赖项管理器并在 IDE 中刷新项目,确保它们可用于您的项目。

通过检索连接 URI(也称为连接字符串 )完成以下步骤,连接到MongoDB 部署。连接 URI 指示驾驶员如何连接到MongoDB 部署以及连接时如何表现。

1

要检索MongoDB 部署的连接字符串,日志登录您的Atlas帐户并导航到 Database 部分下的 Clusters 页面。单击新部署的 Connect 按钮。

Atlas 用户界面的集群部分中的连接按钮

如果您尚未配置数据库用户, MongoDB会提示您创建并配置新用户。

单击 Connect to your application 下的 Drivers 按钮,从 Driver 选择菜单中选择“Java”,然后从 Version 选择菜单中选择与您安装的版本最匹配的版本。

确保取消选择 View full code sample 选项以仅查看连接字符串。

2

单击连接string右侧的按钮将其复制到剪贴板,如以下屏幕截图所示:

Atlas 用户界面中的连接字符串复制按钮
3

将此连接字符串粘贴到首选文本编辑器中的文件中,并将 <db_password> 占位符替换为数据库用户的密码。连接字符串已填充数据库用户的用户名。

将此文件保存到安全位置,以便在下一步中使用。

完成 Spring Data 教程并访问连接 URI 后,您可以将 Spring Session MongoDB添加到应用程序以启用会话管理。

1

导航到application.properties 目录中的src/main/resources 文件。确保此文件指定您的MongoDB 数据库、连接 URI 以及要插入的文档数量,如 Spring Data 教程的配置 MongoClient 部分中所述。如果配置正确,您的文件将包含以下代码:

mongodb.database=bulk
mongodb.uri=<connection URI>
documentCount=25000

<connection URI> 占位符替换为您在上一节中保存的连接 URI。

2

在项目的基础包目录中创建一个名为 SessionConfig.java 的新文件,然后粘贴以下代码:

package com.mongodb.examples.springdatabulkinsert;
import org.mongodb.spring.session.config.annotation.web.http.EnableMongoHttpSession;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableMongoHttpSession
public class SessionConfig {
}

此配置类为您的 Spring Boot应用程序启用MongoDB支持的HTTP会话管理。

接下来,添加 Web 端点,以演示处理来自 Spring Data MongoDB应用程序的产品数据时的会话管理。

1

在项目的基础包目录中创建一个名为 ProductWebController.java 的文件,然后粘贴以下代码:

package com.mongodb.examples.springdatabulkinsert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
public class ProductWebController {
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping("/products/search")
public Map<String, Object> searchProducts(
@RequestParam(required = false) String name,
HttpSession session) {
@SuppressWarnings("unchecked")
List<String> searchHistory = (List<String>) session.getAttribute("searchHistory");
if (searchHistory == null) {
searchHistory = new ArrayList<>();
}
// Defines the default search if no name is provided
if (name == null || name.trim().isEmpty()) {
name = "product";
}
// Adds the current search to history
searchHistory.add(name);
session.setAttribute("searchHistory", searchHistory);
// Queries the "name" field in the "products" collection
Query query = new Query(Criteria.where("name").regex(name, "i"));
List<Product> products = mongoTemplate.find(query, Product.class, "products");
return Map.of(
"products", products,
"sessionId", session.getId()
);
}
@GetMapping("/products/history")
public Map<String, Object> getSearchHistory(HttpSession session) {
// Retrieves the search history from the session
@SuppressWarnings("unchecked")
List<String> searchHistory = (List<String>) session.getAttribute("searchHistory");
if (searchHistory == null) {
searchHistory = new ArrayList<>();
}
return Map.of(
"searchHistory", searchHistory,
"sessionId", session.getId(),
"searchCount", searchHistory.size()
);
}
}

ProductWebController.java 是一个 REST 控制器,它通过与现有产品数据交互来演示会话功能。此文件定义了以下 Web 端点:

  • /products/search:搜索 bulk.products集合中的产品并将每个搜索术语存储在用户会话中

  • /products/history:从MongoDB中存储的用户会话中检索搜索历史数据

2

在测试新的 Web 端点之前,更新主应用程序类以使应用程序保持运行并输出有关端点的信息。将 SpringDataBulkInsertApplication.java 的内容替换为以下代码:

package com.mongodb.examples.springdatabulkinsert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataBulkInsertApplication implements CommandLineRunner {
@Value("${documentCount}")
private int count;
private static final Logger LOG = LoggerFactory
.getLogger(SpringDataBulkInsertApplication.class);
@Autowired
private ProductRepository repository;
public static void main(String[] args) {
SpringApplication.run(SpringDataBulkInsertApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
repository.bulkInsertProducts(count);
LOG.info("Bulk insert completed. Web endpoints are now available.");
LOG.info("You can visit these URLs:");
LOG.info(" http://localhost:8080/products/search?name=goose");
LOG.info(" http://localhost:8080/products/history");
}
}

最后,按照本节中的步骤运行应用程序并探索会话存储功能。

1

在 IDE 中运行应用程序,或在终端中运行以下命令:

./mvnw spring-boot:run

您的应用程序启动,执行批量插入操作,然后在 http://localhost:8080 处提供 Web 端点。

2

打开 Web 浏览器或使用 curl 等工具测试以下启用会话的端点:

  1. 搜索产品:要查询插入bulk.products 集合的文档,请访问http://localhost:8080/products/search?name= 并将产品名称附加到URL。示例,您可以通过访问name "goose"http://localhost:8080 /products/ 搜索 ?name=goose搜索 值为 的文档。

    输出包含您的会话ID以及与您的 name字段查询匹配的文档列表,如以下示例输出所示:

    {
    "sessionId": "...",
    "products": [
    {
    "name": "goose",
    "qty": 788,
    "price": 9680,
    "available": "...",
    "unavailable": "...",
    "skuId": "276-68-7836"
    },
    {
    "name": "goose",
    "qty": 984,
    "price": 2307,
    "available": "...",
    "unavailable": "...",
    "skuId": "068-88-9345"
    },
    ...
    ]
    }
  2. 查看搜索历史记录:要查看搜索历史记录,请访问 http://localhost:8080 /products/history。

    输出包含您的 会话ID、您搜索的产品名称列表以及总搜索次数,如以下示例输出所示:

    {
    "sessionId": "...",
    "searchHistory": [
    "goose",
    "bear"
    ],
    "searchCount": 2
    }
3

如果您停止应用程序并再次运行它, MongoDB会保留您的会话数据。

在 IDE 或终端中停止应用程序。然后重新启动
在 IDE 中运行,或在终端中运行以下命令:
./mvnw spring-boot:run

如果访问 http://localhost:8080 /products/history URL ,则即使应用程序重新启动,仍可查看以前的搜索历史记录。此数据仍然可用,因为它存储在MongoDB中而不是内存中。

注意

会话超时

春季会话 MongoDB 的默认会话超时为 30 分钟。如果应用程序在不活动 30 分钟后重新启动,会话将过期, MongoDB不再存储以前的会话数据。

恭喜您完成本教程!

注意

如果您在本教程中运行问题,请使用此页面右侧或右下角的 Rate this page标签页提交反馈。

您可以使用MongoDB Stack Overflow标签 或MongoDB Reddit Community 寻求一般问题的支持。

在本教程中,您更新了 Spring Data MongoDB应用程序以使用 Spring Session MongoDB ,并将用户会话存储在包含产品数据的同一MongoDB 部署中。该应用程序演示了会话管理与批量操作和数据查询的协同工作。

要继续开发应用程序,请查看以下资源:

后退

春季会话MongoDB

在此页面上