mongodb 是一种非关系型数据库,也被称为 nosql 数据库,它主要以文档的形式存储数据。这些文档的格式通常是 bson(一种包含类型的 json 格式)。下面是 mongodb 的一些核心原理:
文档模型:
- 在 mongodb 中,数据被存储为文档,这些文档类似于 json 对象。每个文档都有一组键值对,值可以是各种数据类型(如字符串、数字、数组、文档等)。
- 文档可以容纳复杂的嵌套结构,这使得 mongodb 在存储复杂和多层次的数据方面非常灵活。
集合:
- 文档被组织在集合中,集合类似于关系数据库中的表。不同的是,集合内的文档不需要有相同的结构,这种模式的灵活性是 mongodb 的一个显著特点。
索引:
- 为了提高查询效率,mongodb 支持对文档中的一个或多个字段建立索引。索引可以显著提高查询速度。
查询语言:
- mongodb 提供了一个功能强大的查询语言,支持文档的各种查询操作,包括字段查找、范围查询、正则表达式搜索等。
- 查询可以返回完整的文档或者只是部分字段,还可以进行排序和分组。
复制和高可用性:
- mongodb 支持数据的自动复制,提高数据的可用性和灾难恢复能力。通过复制集,数据可以在多个服务器之间复制,确保数据的安全性和高可用性。
- 在复制集中,可以有一个主节点和多个从节点,主节点处理所有写操作,从节点可以用于读操作以及在主节点故障时自动接管角色成为新的主节点。
分片:
- 对于大规模数据集,mongodb 支持分片技术,即数据分布在多个服务器上,以便可以扩展数据库的存储容量和查询处理能力。
- 分片可以根据预定义的规则自动进行,使得数据管理更加高效。
简单场景案例
让我们来构建一个使用 spring boot 和 mongodb 的简单博客系统。这个系统将允许用户创建、读取、更新和删除博客文章。我们将包括用户认证和授权的功能,以确保用户只能编辑和删除他们自己的文章。
技术栈
- spring boot: 用于创建 restful api。
- mongodb: 作为后端数据库。
- spring data mongodb: 提供 mongodb 的集成和数据访问操作。
- spring security: 用于用户认证和授权。
项目结构
这个项目将包含以下几个主要部分:
- 模型 (
post,user) - 仓库 (
postrepository,userrepository) - 服务 (
postservice,userservice) - 控制器 (
postcontroller,usercontroller) - 安全配置 (
securityconfig)
步骤
1. 设置 spring boot 项目
首先,使用 spring initializr 创建一个新的 spring boot 项目。选择以下依赖:
- spring web
- spring data mongodb
- spring security
2. 配置 mongodb
在 application.properties 文件中配置 mongodb 数据库连接:
spring.data.mongodb.uri=mongodb://localhost:27017/blog
3. 定义模型
// post.java
package com.example.blog.model;
import org.springframework.data.annotation.id;
import org.springframework.data.mongodb.core.mapping.document;
import java.util.date;
@document
public class post {
@id
private string id;
private string title;
private string content;
private date createdat;
private string authorid;
// getters and setters
}
// user.java
package com.example.blog.model;
import org.springframework.data.annotation.id;
import org.springframework.data.mongodb.core.mapping.document;
@document
public class user {
@id
private string id;
private string username;
private string password;
private string role;
// getters and setters
}
4. 创建仓库
// postrepository.java
package com.example.blog.repository;
import com.example.blog.model.post;
import org.springframework.data.mongodb.repository.mongorepository;
public interface postrepository extends mongorepository<post, string> {
}
// userrepository.java
package com.example.blog.repository;
import com.example.blog.model.user;
import org.springframework.data.mongodb.repository.mongorepository;
public interface userrepository extends mongorepository<user, string> {
user findbyusername(string username);
}
5. 服务层
// postservice.java
package com.example.blog.service;
import com.example.blog.model.post;
import com.example.blog.repository.postrepository;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import java.util.list;
@service
public class postservice {
@autowired
private postrepository postrepository;
public list<post> getallposts() {
return postrepository.findall();
}
public post getpostbyid(string id) {
return postrepository.findbyid(id).orelse(null);
}
public post createpost(post post) {
post.setcreatedat(new date());
return postrepository.save(post);
}
public post updatepost(string id, post updatedpost) {
return postrepository.findbyid(id)
.map(post -> {
post.settitle(updatedpost.gettitle());
post.setcontent(updatedpost.getcontent());
return postrepository.save(post);
}).orelse(null);
}
public void deletepost(string id) {
postrepository.deletebyid(id);
}
}
// userservice.java
package com.example.blog.service;
import com.example.blog.model.user;
import com.example.blog.repository.userrepository;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
@service
public class userservice {
@autowired
private userrepository userrepository;
public user createuser(user user) {
return userrepository.save(user);
}
}
6. 控制器
// postcontroller.java
package com.example.blog.controller;
import com.example.blog.model.post;
import com.example.blog.service.postservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import java.util.list;
@restcontroller
@requestmapping("/api/posts")
public class postcontroller {
@autowired
private postservice postservice;
@getmapping
public list<post> getallposts() {
return postservice.getallposts();
}
@getmapping("/{id}")
public post getpostbyid(@pathvariable string id) {
return postservice.getpostbyid(id);
}
@postmapping
public post createpost(@requestbody post post) {
return postservice.createpost(post);
}
@putmapping("/{id}")
public post updatepost(@pathvariable string id, @requestbody post post) {
return postservice.updatepost(id, post);
}
@deletemapping("/{id}")
public void deletepost(@pathvariable string id) {
postservice.deletepost(id);
}
}
// usercontroller.java
package com.example.blog.controller;
import com.example.blog.model.user;
import com.example.blog.service.userservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/api/users")
public class usercontroller {
@autowired
private userservice userservice;
@postmapping
public user createuser(@requestbody user user) {
return userservice.createuser(user);
}
}
7. 安全配置
// securityconfig.java
package com.example.blog.config;
import org.springframework.context.annotation.configuration;
import org.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.crypto.password.passwordencoder;
@configuration
@enablewebsecurity
public class securityconfig extends websecurityconfigureradapter {
@override
protected void configure(httpsecurity http) throws exception {
http
.csrf().disable()
.authorizerequests()
.antmatchers("/api/posts/**").authenticated()
.antmatchers("/api/users/**").permitall()
.and()
.httpbasic();
}
@override
protected void configure(authenticationmanagerbuilder auth) throws exception {
passwordencoder encoder = new bcryptpasswordencoder();
auth.inmemoryauthentication()
.withuser("user").password(encoder.encode("password")).roles("user")
.and()
.withuser("admin").password(encoder.encode("admin")).roles("admin");
}
}
以上就是在springboot中使用mongodb的简单场景案例的详细内容,更多关于springboot使用mongodb的资料请关注代码网其它相关文章!
发表评论