本文共 5109 字,大约阅读时间需要 17 分钟。
Spring Boot 和 MongoDB 是现代开发中常用的技术工具之一。本文将以一个简单的案例为切入点,展示如何在 Spring Boot 项目中使用 MongoDB 实现缓存功能。虽然 MongoDB 通常被用作非关系型数据库,但在本次案例中,我们仅利用其存储和查询特性来实现简单的缓存功能。对于更复杂的场景,建议参考 MongoDB 的官方文档或相关学习资料。
打开 Studio 3T 等 MongoDB 管理工具,首先连接本地 MongoDB 实例。然后,创建一个名为 test 的数据库,在 test 数据库中创建一个名为 news 的集合。这样,我们就为后续操作做好了准备。
在 IDEA 中创建一个新的 Spring Boot 项目,选择 Java 8 作为编译版本。在模块选择页面中,勾选 Spring Web 和 MongoDB 依赖模块。项目创建完成后,选择合适的位置保存。
创建项目后,我们需要完成一些预备工作以便实现缓存功能。首先,在项目的 application.properties 文件中添加 MongoDB 连接配置,规则如下:
spring.data.mongodb.uri=mongodb://localhost:27017/test
这里,localhost:27017 是 MongoDB 的默认端口地址,test 是我们创建的数据库名称。通过这些配置,项目将能够连接到本地 MongoDB 实例。
接下来,创建项目目录结构,分别包含 controller、service 和 pojo 文件夹。在 controller 文件夹中创建 newsController.java 类,负责 URL 处理和逻辑控制。
package com.mongodemo.controller;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class NewsController { private static final Logger logger = LoggerFactory.getLogger(NewsController.class); // 其他方法的实现代码...} 接下来,我们开始实现 MongoDB 的缓存查询功能。首先,在 NewsService 类中添加一个方法 getNewsByTitle,用于根据标题查询新闻数据。
package com.mongodemo.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.stereotype.Service;@Servicepublic class NewsService { private static final Logger logger = LoggerFactory.getLogger(NewsService.class); @Autowired private MongoTemplate mongoTemplate; public news getNewsByTitle(String title) { Query query = Criteria.where("title").is(title); news news = mongoTemplate.findOne(query, news.class); if (news == null) { logger.info("从数据库查询数据"); news news1 = new news(title, new Date(), "", "bigsai"); news1.setBrief("有了博学谷,妈妈再也不用担心我的java学习!"); news1.setContent("博学谷优质学习资料为java学习提供更好环境,越来越多开发者学习使用"); mongoTemplate.insert(news1, "news"); logger.info("数据插入到MongoDB成功"); return news1; } else { logger.info("数据从缓存访问成功"); return news; } } // 其他方法的实现代码...} 在 NewsController 类中,添加一个 getnews 方法,用于处理用户的 GET 请求。
package com.mongodemo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@Autowiredprivate NewsService newsService;@GetMapping("getnews/{title}")public news getnews(@PathVariable String title) { return newsService.getNewsByTitle(title);} 为了确保 MongoDB 缓存与数据库数据的一致性,我们需要实现缓存的更新和删除功能。
在 NewsService 类中添加一个 updateNewsContentByTitle 方法,用于根据标题更新新闻内容。
package com.mongodemo.service;import org.springframework.data.mongodb.core.UpdateOperations;import org.springframework.data.mongodb.core.query.Query;import org.springframework.data.mongodb.core.query.Update;public class NewsService { // 其他方法的实现代码... public boolean updateNewsContentByTitle(String title, String content) { try { Query query = Criteria.where("title").is(title); Update update = new Update(); update.set("content", content); update.set("date", new Date()); mongoTemplate.upsert(query, update, news.class); } catch (Exception e) { return false; } return true; }} 在 NewsController 类中,添加一个 updatenews 方法,用于处理更新请求。
package com.mongodemo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@Autowiredprivate NewsService newsService;@GetMapping("updatenews")public String updatenews(@PathVariable String title, @PathVariable String content) { boolean result = newsService.updateNewsContentByTitle(title, content); if (result) { return "更新成功"; } else { return "更新失败"; }} 最后,我们需要实现缓存的删除功能。在 NewsService 类中添加一个 deleteNewsByTitle 方法。
public boolean deleteNewsByTitle(String title) { try { Query query = Criteria.where("title").is(title); mongoTemplate.remove(query, news.class); } catch (Exception e) { return false; } return true;} 在 NewsController 类中,添加一个 deletenews 方法,用于处理删除请求。
package com.mongodemo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@Autowiredprivate NewsService newsService;@GetMapping("deletenews/{title}")public String deletenews(@PathVariable String title) { try { newsService.deleteNewsByTitle(title); return "删除成功"; } catch (Exception e) { return "删除失败"; }} 通过上述步骤,我们成功实现了一个基于 Spring Boot 和 MongoDB 的新闻缓存系统。从查询到更新和删除,所有操作都通过 MongoDB 实现,确保了数据的一致性和缓存的有效性。这个案例适合用于入门学习或小型项目开发,帮助开发者快速掌握 MongoDB 的基本操作和缓存机制。
转载地址:http://jvvkz.baihongyu.com/