适合场景:事件记录、内容管理或者博客平台,比如评论系统。
mongodb与mysql不同,mysql的每一次更新操作都会直接写入硬盘,但是mongo不会,做为内存型数据库,数据操作会先写入内存,然后再会持久化到硬盘中去,那么mongo是如何持久化的呢
mongodb在启动时,专门初始化一个线程不断循环(除非应用crash掉),用于在一定时间周期内来从defer队列中获取要持久化的数据并写入到磁盘的journal(日志)和mongofile(数据)处,当然因为它不是在用户添加记录时就写到磁盘上,所以按mongodb开发者说,它不会造成性能上的损耗,因为看过代码发现,当进行CUD操作时,记录(Record类型)都被放入到defer队列中以供延时批量(groupcommit)提交写入,但相信其中时间周期参数是个要认真考量的参数,系统为90毫秒,如果该值更低的话,可能会造成频繁磁盘操作,过高又会造成系统宕机时数据丢失过。
下面就记录一下在spring boot中怎么配置和连接mongodb
1.pom.xml
xml version="1.0" encoding="UTF-8"?>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"> 4.0.0 com.mongodb.demo mongodbdemo 0.0.1-SNAPSHOT jar mongodbdemo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.12.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-devtools true true com.alibaba fastjson 1.2.38 org.springframework.boot spring-boot-starter-freemarker junit junit 3.8.1 test org.junit.jupiter junit-jupiter-api RELEASE junit junit RELEASE org.springframework.boot spring-boot-maven-plugin
2.在classpath下加上application.properties ,文件中加上以下内容
spring.application.name=mongodbdemo # mongodb spring.data.mongodb.uri=mongodb://appuser:[email protected]:27017/paas_message_center
3.实体类
package com.mongodb.demo.mongodbdemo.domain; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -3258839839160856613L; private Long id; private String userName; private String passWord; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + '}'; } }
4.Dao
package com.mongodb.demo.mongodbdemo.dao; import com.mongodb.demo.mongodbdemo.domain.User; import java.util.List; public interface UserDao { public void saveUser(User user); public User findUserById(long id); public User findUserByUserName(String userName); public void updateUser(User user); public void deleteUserById(Long id); public ListfindAll(int pageNo, int pageSize); public List list(); }
package com.mongodb.demo.mongodbdemo.dao.impl; import com.mongodb.demo.mongodbdemo.dao.UserDao; import com.mongodb.demo.mongodbdemo.domain.User; import org.springframework.data.domain.Sort; 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.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service("userDao") public class UserDaoImpl implements UserDao{ @Resource private MongoTemplate mongoTemplate; @Override public void saveUser(User user) { mongoTemplate.save(user); } @Override public User findUserById(long id) { Query query = new Query(Criteria.where("id").is(id)); return mongoTemplate.findOne(query,User.class); } @Override public User findUserByUserName(String userName) { Query query = new Query(Criteria.where("userName").is(userName)); User user = mongoTemplate.findOne(query , User.class); return user; } @Override public void updateUser(User user) { Query query=new Query(Criteria.where("id").is(user.getId())); Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); //更新查询返回结果集的第一条 mongoTemplate.updateFirst(query,update,User.class); //更新查询返回结果集的所有 // mongoTemplate.updateMulti(query,update,User.class); } @Override public void deleteUserById(Long id) { Query query=new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,User.class); } @Override public ListfindAll(int pageNo, int pageSize) { Query query = new Query(); query.skip((pageNo - 1) * pageSize); query.limit(pageSize); query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "userId")));//按照userId排序 List users = mongoTemplate.find(query,User.class); return users; } @Override public List list() { Query query = new Query(); List users = mongoTemplate.find(query,User.class); return users; } }
5.创建测试类
package com.mongodb.demo.mongodbdemo; import com.mongodb.demo.mongodbdemo.dao.UserDao; import com.mongodb.demo.mongodbdemo.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class UserDaoTest { @Resource private UserDao userDao; @Test public void testSaveUser() throws Exception { User user=new User(); user.setId(3L); user.setUserName("小彭"); user.setPassWord("123456"); userDao.saveUser(user); } @Test public void findUserByUserName(){ User user= userDao.findUserByUserName("小王"); System.out.println("user is "+user); } @Test public void updateUser(){ User user=new User(); user.setId(2l); user.setUserName("天空"); user.setPassWord("fffxxxx"); userDao.updateUser(user); } @Test public void deleteUserById(){ userDao.deleteUserById(1l); } @Test public void listTest() { Listusers = userDao.list(); System.out.println(users.size()); for(User user:users) { System.out.println(user.toString()); } } @Test public void findUserByIdTest() { User user = userDao.findUserById(1L); System.out.println(user.toString()); } }
在虚拟机中安装MongonDB ,docker安装命令如下:
docker pull mongo:3.4.9
docker run -p 27017:27017 --name mongodb -d mongo:3.4.9 --auth
docker exec -it mongodb mongo admin
db.createUser({user:"root",pwd:"123456",roles:["root"]});
#创建数据库存
paas_message_center
appuser
123456