一、Mongodb集群安装
本文介绍基于mongodb的副本机制搭建集群
192.168.139.186 | CentOS Linux release 7.7.1908 (Core) |
192.168.139.187 | CentOS Linux release 7.7.1908 (Core) |
192.168.139.188 | CentOS Linux release 7.7.1908 (Core) |
准备工作
- 关闭selinux,关闭防火墙(或者开放端口)及安装软件包,在3台服务器上都执行。
#关闭Selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
#开启端口号27017
firewall-cmd --permanent --add-port=27017/tcp
firewall-cmd --reload
#关闭防火墙
systemctl stop firewalld
#安装工具
dnf -y install net-tools bash-completion vim wget
#重启
reboot
注意:如果安装工具包报错,执行以下命令
yum install epel-release
yum install dnf -y
dnf -y install net-tools bash-completion vim wget
2、解压缩文件
#解压缩
tar -zxvf mongodb-linux-x86_64-enterprise-rhel70-6.0.3.tgz
#移动文件
mv mongodb-linux-x86_64-enterprise-rhel70-6.0.3 /usr/local/mongodb
3、创建文件
mkdir -p /data/mongodb/{conf,log,data,key}
4、配置文件在/data/mongodb/conf/目录下创建mongod.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/log/mongodb.log
storage:
dbPath: /data/mongodb/data/
journal:
enabled: true
processManagement:
fork: true
timeZoneInfo: /usr/share/zoneinfo
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: mycluster
security:
authorization: enabled
keyFile: /data/mongodb/key/mongo.keyfile
以上操作在每一台服务器上都执行
5、生成key用于服务间通信
在任意一台服务器上执行如下指令
#生成key
openssl rand -base64 753 > /data/mongodb/key/mongo.keyfile
#授权
chmod 600 /data/mongodb/key/mongo.keyfile
#进入key目录
cd /data/mongodb/key
#复制mongo.keyfile到另外两台服务器
scp -r mongo.keyfile 192.168.139.188:/data/mongodb/key/
scp -r mongo.keyfile 192.168.139.187:/data/mongodb/key/
6、启动服务(每个服务器上都要启动)
/usr/local/mongodb/bin/mongod -f /data/mongodb/conf/mongod.conf
如果报错
/usr/local/mongodb/bin/mongod: error while loading shared libraries: libnetsnmpmibs.so.31: cannot open shared object file: No such file or directory
该error 是因为未装net-snmp执行以下命令
yum install net-snmp -y
7、连接客户端
具体参考我的上一篇博客
Linux安装mongodb社区版_熟透的蜗牛的博客-CSDN博客
./mongosh 192.168.139.187
#配置集群信息
config = { _id:"mycluster", members:[
{_id:0,host:"192.168.139.186:27017"},
{_id:1,host:"192.168.139.187:27017"},
{_id:2,host:"192.168.139.188:27017"}]
};
rs.initiate( config )
#查看状态
rs.status()
#创建用户
#创建用户
use admin;
db.createUser({user: 'root', pwd: '123456', roles: [{role: 'root', db: 'admin'}]});
db.createUser({user: 'admin', pwd: '123456', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});
db.createUser({
user: 'user',
pwd: '123456',
roles: [
{ role: "dbAdmin", db: "mydb" },
{ role: "readWrite", db: "mydb" }
]
});
#删除用户
db.system.users.remove({user:"用户名"}) 删除用户
db.system.users.remove({_id:"用户id"}) 根据id删除
9、连接客户端
#使用密码连接
./mongosh 192.168.138.187 -u root -p 123456
可知 第二个服务器为主节点
#在主节点上添加数据
Enterprise mycluster [direct: primary] admin> use mydb
switched to db mydb
Enterprise mycluster [direct: primary] mydb> db.myuser.insertOne( {'name': 'mytest'} )
切换连接
./mongosh 192.168.138.187 -u root -p 123456
可见从节点不支持写操作,而且也不支持读操作。
#从库需要指定为从库才能查询数据
rs.secondaryOk() ;
db.myuser.find();
10、设置优先级
conf = rs.config();
conf.members[0].priority = 10;
conf.members[1].priority = 5;
conf.members[2].priority = 2;
rs.reconfig(conf); #主节点执行
#各个节点的优先级默认均为1,如果优先级为0则没有被选举为主节点的被选举权,只有选举权。
#如果关闭主节点,其他从节点根据优先级选举为主节点
二、整合SpringBoot
application.yml
spring:
application:
name: test-springboot
servlet:
multipart:
enabled: true #开启文件上传
max-file-size: 200MB #限制文件上传大小为10M
file-size-threshold: 200MB #单个文件大小限制
max-request-size: 200MB
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
mode: HTML5
servlet:
content-type: text/html
main:
allow-bean-definition-overriding: true
data:
mongodb:
# uri: mongodb://192.168.178.134:27017,192.168.178.136:27017,192.168.178.137:27017/mydb?maxPoolSize=512 不带密码
uri: mongodb://user:123456@192.168.139.186:27017,192.168.139.187:27017,192.168.139.188:27017/mydb?maxPoolSize=512 #带密码连接
maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
service
package com.xiaojie.mongodb.service;
import com.mongodb.client.result.UpdateResult;
import com.xiaojie.mongodb.model.TestUser;
import lombok.extern.slf4j.Slf4j;
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.Service;
import java.util.Date;
import java.util.List;
/**
* @author 熟透的蜗牛
* @version 1.0
* @description: mongodb 正增删改查
* @date 2023/1/6 0:03
*/
@Service
@Slf4j
public class TestUserServiceImpl implements TestUserService {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public List<TestUser> listByPage(int page, int pageSize) {
Query skip = new Query().skip((page - 1) * pageSize).limit(pageSize);
return mongoTemplate.find(skip, TestUser.class);
}
@Override
public void saveTestUser() {
for (int i = 0; i < 1000; i++) {
TestUser build = TestUser.builder().id(1000L + i)
.pin("admin")
.userName("admin")
.nickName("熟透的蜗牛")
.trueName("熟透的蜗牛")
.gender(1).mobile("15202205170").phone("110")
.email("whisper_snali@163.com")
.head("www.baidu.com")
.deptId(100000L)
.status(1)
.isDelete(0)
.postStatus(1).created("admin").updated("admin").createTime(new Date()).updateTime(new Date()).build();
TestUser save = mongoTemplate.save(build);
}
}
@Override
public void updateTestUser(Long userId) {
Query query = new Query();
query.addCriteria(Criteria.where("id").lt(userId));
query.addCriteria(Criteria.where("mobile").is("15202205170"));
Update update = new Update().set("createTime", new Date()).set("updateTime", new Date());
mongoTemplate.updateFirst(query, update, TestUser.class);
UpdateResult updateResult = mongoTemplate.updateMulti(query, update, TestUser.class);
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", updateResult);
}
@Override
public void removeByUserId(Long userId) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(userId));
mongoTemplate.remove(query, TestUser.class);
}
}
Navicat 连接mongodb 可视化工具
完整代码:spring-boot: Springboot整合redis、消息中间件等相关代码 mongodb模块。