Restful: Spring Boot with Mongodb

为什么是mongodb?

继续之前的dailyReport项目,今天的任务是选择mongogdb作为持久化存储。

关于nosql和rdbms的对比以及选择,我参考了不少资料,关键一点在于:nosql可以轻易扩展表的列,对于业务快速变化的应用场景非常适合;rdbms则需要安装关系型数据库模式对业务进行建模,适合业务场景已经成熟的系统。我目前的这个项目——dailyReport,我暂时没法确定的是,对于一个report,它的属性应该有哪些:date、title、content、address、images等等,基于此我选择mongodb作为该项目的持久化存储。

如何将mongodb与spring boot结合使用

  • 修改Pom文件,增加mongodb支持
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
  • 重新设计Report实体类,id属性是给mongodb用的,用@Id注解修饰;重载toString函数,使用String.format输出该对象。
import org.springframework.data.annotation.Id;

/**
 * @author duqi
 * @create 2015-11-17 19:31
 */
public class Report {

    @Id
    private String id;

    private String date;
    private String content;
    private String title;

    public Report() {

    }

    public Report(String date, String title, String content) {
        this.date = date;
        this.title = title;
        this.content = content;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String dateStr) {
        this.date = dateStr;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return String.format("Report[id=%s, date='%s', content='%s', title='%s']", id, date, content, title);
    }
}
  • 增加ReportRepository接口,它继承自MongoRepository接口,MongoRepository接口包含了常用的CRUD操作,例如:save、insert、findall等等。我们可以定义自己的查找接口,例如根据report的title搜索,具体的ReportRepository接口代码如下:
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * Created by duqi on 15/11/22.
 */
public interface ReportRepository extends MongoRepository<Report, String> {
    Report findByTitle(String title);
    List<Report> findByDate(String date);
}
  • 修改ReportService代码,增加createReport函数,该函数根据Conroller传来的Map参数初始化一个Report对象,并调用ReportRepository将数据save到mongodb中;对于getReportDetails函数,仍然开启缓存,如果没有缓存的时候则利用findByTitle接口查询mongodb数据库。
import com.javadu.dailyReport.domain.Report;
import com.javadu.dailyReport.domain.ReportRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author duqi
 * @create 2015-11-17 20:05
 */

@Service
public class ReportService {

    @Autowired
    private ReportRepository repository;

    public Report createReport(Map<String, Object> reportMap) {
        Report report = new Report(reportMap.get("date").toString(),
                reportMap.get("title").toString(),
                reportMap.get("content").toString());

        repository.save(report);
        return report;
    }

    @Cacheable(value = "reportcache", keyGenerator = "wiselyKeyGenerator")
    public Report getReportDetails(String title) {
        System.out.println("无缓存的时候调用这里---数据库查询, title=" + title);
        return repository.findByTitle(title);
    }
}

Restful接口

Controller只负责URL到具体Service的映射,而在Service层进行真正的业务逻辑处理,我们这里的业务逻辑异常简单,因此显得Service层可有可无,但是如果业务逻辑复杂起来(比方说要通过RPC调用一个异地服务),这些操作都需要再service层完成。总体来讲,Controller层只负责:转发请求 + 构造Response数据;在需要进行权限验证的时候,也在Controller层利用aop完成。

一般将对于Report(某个实体)的所有操作放在一个Controller中,并用@RestController和@RequestMapping("/report")注解修饰,表示所有xxxx/report开头的URL会由这个ReportController进行处理。

. POST

对于增加report操作,我们选择POST方法,并使用@RequestBody修饰POST请求的请求体,也就是createReport函数的参数;

. GET

对于查询report操作,我们选择GET方法,URL的形式是:“xxx/report/${report's title}”,使用@PathVariable修饰url输入的参数,即title。

import com.javadu.dailyReport.domain.Report;
import com.javadu.dailyReport.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author duqi
 * @create 2015-11-17 20:10
 */

@RestController
@RequestMapping("/report")
public class ReportController {
    private static final Logger logger = LoggerFactory.getLogger(ReportController.class);

    @Autowired
    ReportService reportService;

    @RequestMapping(method = RequestMethod.POST)
    public Map<String, Object> createReport(@RequestBody Map<String, Object> reportMap) {
        logger.info("createReport");
        Report report = reportService.createReport(reportMap);

        Map<String, Object> response = new LinkedHashMap<String, Object>();
        response.put("message", "Report created successfully");
        response.put("report", report);

        return response;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{reportTitle}")
    public Report getReportDetails(@PathVariable("reportTitle") String title) {
        logger.info("getReportDetails");
        return reportService.getReportDetails(title);
    }
}

Update和delete操作我这里就不一一讲述了,留个读者作为练习

参考资料

  1. sql vs nosql: what you need to know
  2. Accessing data with Mongodb
  3. Spring Boot:Restful API using Spring Boot and Mongodb
时间: 2024-08-03 14:33:49

Restful: Spring Boot with Mongodb的相关文章

springboot(十一):Spring boot中mongodb的使用

mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置漏洞被攻击,数据被删,引起了人们的注意,感兴趣的可以看看这篇文章:场屠戮MongoDB的盛宴反思:超33000个数据库遭遇入侵勒索,同时也说明了很多公司生产中大量使用mongodb. mongodb简介 MongoDB(来自于英文单词"Humongous",中文含义为"庞大&qu

spring boot集成mongodb最简单版

通过spring tools suite新建一个spring project.带maven的即可 pom.xml文件配置 001 <?xml version="1.0" encoding="UTF-8"?> 002 <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&

5.12. Spring boot with MongoDB

5.12.1. Maven pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&qu

Docker with Spring Boot

前段时间在我厂卷爷的指导下将Docker在我的实际项目中落地,最近几个小demo都尽量熟悉docker的使用,希望通过这篇文章分享我截止目前的使用经验(如有不准确的表述,欢迎帮我指出).本文的主要内容是关于Java应用程序的docker化,首先简单介绍了docker和docker-compose,然后利用两个案例进行实践说明. 简单说说Docker,现在云计算领域火得一塌糊涂的就是它了吧.Docker的出现是为了解决PaaS的问题:运行环境与具体的语言版本.项目路径强关联,因此干脆利用lxc技术

基于 MongoDB 及 Spring Boot 的文件服务器的实现

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的,旨在为 WEB 应用提供可扩展的高性能数据存储解决方案.它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型. 本文将介绍通过 MongoDB 存储二进制文件,从而实现一个文件服务器 MongoDB File Server. 文件服务器的需求 本文件服务器致力于小型文件的存储,比如博客中图片.普通文档等.由于MongoDB 支持多种数据格式的存储

RESTful by Spring Boot with MySQL

现在的潮流是前端承担越来越多的责任:MVC中的V和C,后端只需要负责提供数据M,但是后端有更重要的任务:高并发.提供各个维度的扩展能力(负载均衡.数据表切分.服务分离).更清晰的API设计.Spring Boot框架提供的机制便于工程师实现标准的RESTful接口,本文主要讨论如何编写Controller代码,另外还涉及了MySQL的数据库操作,之前我也写过一篇关于Mysql的文章link,但是这篇文章加上了CRUD的操作. 先回顾下之前的文章中我们用到的例子:图书信息管理系统,主要的领域对象有

使用Spring Boot构建RESTful Web服务以访问存储于Aerospike集群

Spring Boot是对Spring快速入门的强大工具.Spring Boot能够帮助你很容易地构建基于Spring的应 用. Aerospike是分布式和可复制的内存数据库,不管使用DRAM还是原生的flash/SSD,Aerospike都进行 了优化. Aerospike具有高可靠性并且遵循ACID.开发人员能够在不停止数据库服务的情况下,很快地将 数据库集群从两个节点扩展到二十个节点. 你所要构建的是什么 本文将会引领你使用Spring Boot创建一个简单的RESTful Web服务.

用Kotlin写一个基于Spring Boot的RESTful服务

Spring太复杂了,配置这个东西简直就是浪费生命.尤其在没有什么并发压力,随便搞一个RESTful服务 让整个业务跑起来先的情况下,更是么有必要纠结在一堆的XML配置上.显然这么想的人是很多的,于是就 有了Spring Boot.又由于Java 8太墨迹于是有了Kotlin. 数据源使用MySql.通过Spring Boot这个基本不怎么配置的,不怎么微的微框架的Spring Data JPA和Hibernate 来访问数据. 处理依赖 这里使用Gradle来处理依赖. 首先下载官网给的初始项

Spring Boot中使用Swagger2构建强大的RESTful API文档

由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端. 这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发.Android开发或是Web开发等.为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTf