首先,先讲一下mongondb为nosql的一些特性,mongoDB 是一种文档性的数据库。先解释一下文档的数据库,即可以存放xml、json、bson类型系那个的数据。这些数据具备自述性(self-describing),呈现分层的树状数据结构。redis可以用hash存放简单关系型数据。
mongoDB 存放json格式数据。
mongoDB 存放json格式数据。
适合场景:事件记录、内容管理或者博客平台,比如评论系统。
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"?> <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"> <modelVersion>4.0.0</modelVersion> <groupId>com.mongodb.demo</groupId> <artifactId>mongodbdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mongodbdemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.38</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.在classpath下加上application.properties ,文件中加上以下内容
spring.application.name=mongodbdemo # mongodb spring.data.mongodb.uri=mongodb://appuser:123456@10.21.156.11: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 List<User> findAll(int pageNo, int pageSize); public List<User> 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 List<User> findAll(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<User> users = mongoTemplate.find(query,User.class); return users; } @Override public List<User> list() { Query query = new Query(); List<User> 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() { List<User> users = 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