10次方项目第二天

第2章 - MongoDB和评论管理

了解什么是MongoDB
掌握MongoDB的安装
掌握MongoDB的常用命令
掌握mongodb-driver的基本使用
掌握SpringDataMongoDB的使用
能够实现文章评论功能开发

1 MongoDB简介

1.1 文章评论数据分析
文章评论功能存在以下特点:

  1. 数据量大
  2. 写入操作频繁
  3. 价值较低

对于这样的数据,我们更适合使用MongoDB来实现数据的存储

1.2 什么是MongoDB

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应 用提供可扩展的高性能数据存储解决方案。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当 中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的 bson格式,因此可以存储比较复杂的数据类型。

1.3 MongoDB特点

Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的 查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对 数据建立索引。
它的特点是高性能、易部署、易使用,存储数据非常方便。主要功能特性有:

  1. 面向集合存储,易存储对象类型的数据。

  2. 模式自由。

  3. 支持动态查询。

  4. 支持完全索引,包含内部对象。

  5. 支持查询。

  6. 支持复制和故障恢复。

  7. 使用高效的二进制数据存储,包括大型对象(如视频等)。

  8. 自动处理碎片,以支持云计算层次的扩展性。

  9. 支持RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。

  10. 文件存储格式为BSON(一种JSON的扩展)。

 **1.4 MongoDB体系结构**

 MongoDB 的逻辑结构是一种层次结构。主要由:文档(document)、集合 (collection)、数据库(database)这三部分组成的。逻辑结构是面向用户的,用户使 用 MongoDB 开发应用程序使用的就是逻辑结构。

 \1. MongoDB 的文档(document),相当于关系数据库中的一行记录。

 \2. 多个文档组成一个集合(collection),相当于关系数据库的表。

 \3. 多个集合(collection),逻辑上组织在一起,就是数据库(database)。 

 \4.一个 MongoDB 实例支持多个数据库(database)。



 **2.MongoDB基本使用**

 **2.1** window系统MongoDB安装

  **1.启动**

 mongod --dbpath=D:\data

 我们在启动信息中可以看到,mongoDB的默认端口是27017,如果我们想改变默 认的启动端口,可以通过--port来指定端口,例如
 mongod --dbpath=D:\data -port 8989



 **2.登录**

 再打开一个新的命令行窗口,执行以下命令:()

 mongo 127.0.0.1:27017

 3.**退出**

 exit

 **2.2 Docker 环境下MongoDB安装**
 在Linux虚拟机中创建mongo容器,命令如下:

 
1
2
3
1. docker run -id --name mongo -p 27017:27017 mongo


​ a. Mongo命令: **2.3.2查询:** 按一定条件来查询,比如查询userid为1013的记录,只要在find()中添加参数即可, 参数也是json格式,如下: db.数据库表名.find({userid:'1013'}) (省略条件则查询所有) 返回指定条数的记录,可以在find方法后调用limit来返回结果,例如: db.comment.find().limit(2) **2.3.3** **修改与删除文档**: 修改文档的语法结构: ###### !!db.集合名称.update(条件,修改后的数据) ###### 执行后发现,这条文档除了thumbup字段其它字段都不见了。 ##### 为了解决这个问题,我们需要使用修改器$set来实现,命令如下: db.comment.update({“条件”},{$set:{"修改的结果"}}) 2.3.4删除文档的语法结构: db.集合名称.remove(条件) **3.1 环境准备****
1
2
3
4
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId> <version>3.10.1</version> </dependency>

**4.1开发准备** 在文章微服务添加依赖:
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>

添加配置文件:
1
2
3
4
5
6
data:
mongodb:
database:数据库表名(Mongo)
host: MongoIp地址


创建映射的实体类,使用lombok方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package xiaohu.tensquare.article.pojo;

import lombok.Data;
import org.springframework.data.annotation.Id;

import java.io.Serializable;
import java.util.Date;
@Data
public class Commentd implements Serializable {
@Id
private String _id;

private String articleid;
private String content;
private String userid;
private String parentid;
private Date publishdate;
private Integer thumbup;


}
注意:编写CommentRepository,注意不要和 MyBatis的接口放在一个包:(单独放在一个repository包中)
1
2
3
public interface CommentRepository extends MongoRepository<Comment, String> {
}

继承该类 ,springDataMongoDb支持通过查询方法名进行查询定义的方式,如:
屏幕截图 2020-10-02 101106
1
2
3
4
5
6
7
//根据文章id查询评论

List<Commentd> findByArticleid(String articleId);

//根据用户Id查询

List<Commentd>findByUserid(String userId);

4.2编写Service,和Controller业务代码,增删改查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
 /**
* 根据id查询评论数据
*
* @param _id
* @return
*/
@RequestMapping(value = "{_id}", method = RequestMethod.GET)
public Result findById(@PathVariable String _id) {
Commentd commentd = commentdService.findById(_id);
return new Result(true, StatusCode.OK, "查询单个成功", commentd);

}
/**
* 评论查询所有
*
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public Result findAll() {
List<Commentd> list = commentdService.findAll();
return new Result(true, StatusCode.OK, "查询成功", list);
}
/**
* 新增文章数据,根据分布式id
*
* @param commentd
* @return
*/
@PostMapping("/save")
public Result saveComment(@RequestBody Commentd commentd) {
commentdService.save(commentd);
return new Result(true, StatusCode.OK, "新增成功");

}

/**
* 根据id修改评论数据
*
* @param commentId
* @param commentd
* @return
*/
@RequestMapping(value = "{commentId}", method = RequestMethod.PUT)
public Result updateComment(@PathVariable String commentId, @RequestBody Commentd commentd) {
commentd.set_id(commentId);
commentdService.udpateByid(commentd);

return new Result(true, StatusCode.OK, "修改成功");
}

/**
* 根据id删除评论数据
*
* @param commentId
* @return
*/
@RequestMapping(value = "{commentId}", method = RequestMethod.DELETE)
public Result deleteComment(@PathVariable String commentId) {
commentdService.delete(commentId);
return new Result(true, StatusCode.OK, "删除成功");

}

/**
* 删除所有评论数据
*
* @return
*/
@RequestMapping(value = "/deleteAll", method = RequestMethod.DELETE)
public Result deleteAll() {
commentdService.delete();
return new Result(true, StatusCode.OK, "删除所有成功");
}

4.3 评论点赞,不能重复点赞

!!使用redis存储用户id信息和文章id信息,导入redis依赖坐标

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**Controller层
* 根据评论Id点赞 点赞相当与更新数据用put请求
*
* @param commentId
* @return
*/
@RequestMapping(value = "/thumbup/{commentId}", method = RequestMethod.PUT)
public Result thumbupCommentId(@PathVariable String commentId) {
//将用户信息存储到redis,防止重复点赞
//每次点赞之前,先查询用户信息,如果没有用户,则可以点赞,redis有就取消点赞
//模拟用户id
String userid = "123";
//查询用户点赞信息,根据用户id评论id
Object flag = redisTemplate.opsForValue().get("thumbup" + userid + "_" + commentId);
//判断查询结果是否为空,为空则没点赞 反之就取消;
if (flag == null) {
commentdService.updateCommentIdAdd(commentId);
redisTemplate.opsForValue().set("thumbup" + userid + "_" + commentId, 1);
return new Result(true, StatusCode.OK, "点赞成功");
//点赞完成,保存用户信息
} else {
commentdService.updateCommentIdReduce(commentId);
//删除redis中的key
redisTemplate.delete("thumbup" + userid + "_" + commentId);
return new Result(true, StatusCode.OK, "取消点赞成功");

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 //Service层的增加点赞和取消点赞的方法,重复点赞则为取消点赞,点赞数不能小于0

public void updateCommentIdAdd(String commentId) {
/*//根据评论id查询评论数据 i++线程不完全
Optional<Commentd> id = commentdRepository.findById(commentId);
//对评论点赞数据加1
if (id.isPresent()) {
Commentd commentd = id.get();
Integer thumbup = commentd.getThumbup();
thumbup+=1;
commentd.setThumbup(thumbup);
//保存修改数据
commentdRepository.save(commentd);
}else {
return ;
}*/

//点赞功能优化,使用模板封装
//封装修改条件
//直接修改数据
//第一个参数为条件
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(commentId));
//第二个参数为修改的数值
Update update = new Update();
update.inc("thumbup", 1);
//第三个参数为集合数据库表
mongoTemplate.updateFirst(query, update, "commentd");
}

public void updateCommentIdReduce(String commentId) {
//取消点赞
Commentd commentd = commentdRepository.findById(commentId).get();
//点赞数不能小于0
if (commentd.getThumbup() > 0) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(commentId));
Update update = new Update();
update.inc("thumbup", -1);
mongoTemplate.updateFirst(query, update, "commentd");
}
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 10次方项目第二天
  2. 2. 1 MongoDB简介
,