1.下载
a.官方下载链接:https://www.mongodb.com/download-center/community,我在这里选择的是这个版本:mongodb-linux-x86_64-ubuntu1604-4.0.3.tgz
b.github链接:https://github.com/mongodb/mongo,这是源码git的路径。也可以进行对源码进行编译安装。
我使用的是a方式(下载速度快些)
2.解压安装:这里只需要解压一下就OK
命令:
tar -zxvf mongodb-linux-x86_64-ubuntu1604-4.0.3.tgz
修改一下文件名字:
mv mongodb-linux-x86_64-ubuntu1604-4.0.3 ./
3.需要加一个配置文件。这个配置文件是第一为了指定数据存储路径,第二是为了指定logs的路径
这个是目录构造:data,conf,log 路径都是我自己手动创建的:mkdir ./log ...等等
4.在conf中添加一个mongodb.conf的一个配置文件,文件内容如下:
#mongoDB的配置文件:
#端口:27017为默认端口
port = 27017
#数据存储相对路径:
dbpath = data
#日志
logpath = log/mongolog.log
#是否以守护进程方式运行
fork = true
#以追加的方式写入日志,为了防止丢失日志
logappend=true
#允许远程访问
bind_ip = 0.0.0.0
5.启动 :
./bin/mongod -f ./conf/mongodb.conf
6.启动成功的界面
7.与项目结合。我使用的java中springboot项目。下面是我的代码:
项目结构:
8.首先先加入pom:
org.springframework.boot
spring-boot-starter-data-mongodb
9.编写配置类:(并且在启动类上面加入配置类的包扫描)
package com.socket.cn.configs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
@Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private Logger logger = LoggerFactory
.getLogger(MongoConfig.class);
@Value("${mongodb.host}")
private String mongodbHost;
@Value("${mongodb.port}")
private int mongodbPort;
@Value("${mongodb.name}")
private String mongodbName;
@Value("${mongodb.user}")
private String mongodbUser;
@Value("${mongodb.password}")
private String mongodbpwd;
@Value("${mongodb.authentification}")
private boolean authentification;
@Bean
@Override
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate =
new MongoTemplate(mongo(), mongodbName);
logger.info("*******"+mongoTemplate.getDb().getName() +"基础库");
return mongoTemplate;
}
@Override
protected String getDatabaseName() {
return mongodbName;
}
@Override
public Mongo mongo() throws Exception {
MongoClient mongoClient;
MongoCredential credential = MongoCredential.createMongoCRCredential(mongodbUser,mongodbName,mongodbpwd.toCharArray());
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(3000)
.threadsAllowedToBlockForConnectionMultiplier(10)
.readPreference(ReadPreference.nearest())
.build();
List addresses = new ArrayList();
String[] str = this.mongodbHost.split(",");
for (String strHost : str) {
ServerAddress address = new ServerAddress(strHost, mongodbPort);
addresses.add(address);
}
if(authentification){
mongoClient = new MongoClient(addresses,Arrays.asList(credential), options);
}else{
mongoClient = new MongoClient(addresses, options);
}
return mongoClient;
}
}
application.properties:
server.port: 9233
mongodb.host=192.168.31.185
mongodb.port=27017
mongodb.name=book_chapter
mongodb.user=admin
mongodb.password=
mongodb.authentification=false
10.上网找了一个通用的dao,这个感觉比较好用,也可以实现快速的开发。
package com.socket.cn.dao;
import org.springframework.data.mongodb.core.query.Update;
public interface BaseDao {
boolean remove(String id);
T get(String id);
void insert(T t);
boolean update(Update update, String id) ;
}
package com.socket.cn.dao.Impl;
import java.lang.reflect.ParameterizedType;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
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.Repository;
import com.mongodb.WriteResult;
import com.socket.cn.dao.BaseDao;
@Repository
public class BaseDaoImp implements BaseDao {
@Autowired
private MongoTemplate mongoTemplate;
private Class clz;
@SuppressWarnings("unchecked")
public Class getClz() {
if (clz==null) {
ParameterizedType genericSuperclass = (ParameterizedType)this.getClass().getGenericSuperclass();
clz = (Class)genericSuperclass.getActualTypeArguments()[0];
}
return clz;
}
@Override
public boolean remove(String id) {
Criteria criteria = Criteria.where("_id").is(new ObjectId(id));
Query query = new Query(criteria);
WriteResult writeResult = mongoTemplate.remove(query, getClz());
return writeResult.getN() > 0 ? true :false;
}
@Override
public T get(String id) {
Criteria criteria = Criteria.where("_id").is(new ObjectId(id));
Query query = new Query(criteria);
return mongoTemplate.findOne(query,getClz());
}
@Override
public void insert(T t) {
mongoTemplate.insert(t);
}
@Override
public boolean update(Update update, String id) {
Criteria criteria = Criteria.where("_id").is(new ObjectId(id));
Query query = new Query(criteria);
WriteResult writeResult =mongoTemplate.updateFirst(query,update,getClz());
return writeResult.getN() > 0 ? true :false;
}
}
11.上面就是我的核心代码。下面举个栗子:
package com.socket.cn.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.socket.cn.bean.BookChapter;
import com.socket.cn.service.BookChapterService;
@RestController
@RequestMapping("/bookChapter")
public class BookChapterController {
@Autowired
private BookChapterService bookChapterService;
@RequestMapping("/insert")
public String insert() {
BookChapter bookChapter = new BookChapter();
bookChapter.setId("adasds");
bookChapter.setBookId(12321);
bookChapter.setChapterContent("收到货广东省外");
bookChapter.setChapterName("广东省");
bookChapter.setCreateTime(new Date());
bookChapter.setUpdateTime(new Date());
bookChapter.setChapterLength(21);
bookChapterService.insert(bookChapter);
return "OK";
}
}
package com.socket.cn.bean;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "book_chapter")//mongodb的表名
public class BookChapter implements Serializable{
private static final long serialVersionUID = -5068780066538441690L;
@Id
private String id;
private Integer bookId;
private Integer chapterId;
private String chapterNumber;
private String chapterName;
private String chapterContent;
private Integer chapterLength;
private Date createTime;
private Date updateTime;
public BookChapter() {
super();
// TODO Auto-generated constructor stub
}
public BookChapter(String id, Integer bookId, Integer chapterId, String chapterNumber, String chapterName,
String chapterContent, Integer chapterLength, Date createTime, Date updateTime) {
super();
this.id = id;
this.bookId = bookId;
this.chapterId = chapterId;
this.chapterNumber = chapterNumber;
this.chapterName = chapterName;
this.chapterContent = chapterContent;
this.chapterLength = chapterLength;
this.createTime = createTime;
this.updateTime = updateTime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public Integer getChapterId() {
return chapterId;
}
public void setChapterId(Integer chapterId) {
this.chapterId = chapterId;
}
public String getChapterNumber() {
return chapterNumber;
}
public void setChapterNumber(String chapterNumber) {
this.chapterNumber = chapterNumber;
}
public String getChapterName() {
return chapterName;
}
public void setChapterName(String chapterName) {
this.chapterName = chapterName;
}
public String getChapterContent() {
return chapterContent;
}
public void setChapterContent(String chapterContent) {
this.chapterContent = chapterContent;
}
public Integer getChapterLength() {
return chapterLength;
}
public void setChapterLength(Integer chapterLength) {
this.chapterLength = chapterLength;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
12.运行结果:成功
1).项目连接成功的日志
2).查看mongo中的数据是否保存。