心灵鸡汤:

加载中...

Mongodb记录用户浏览商品记录

MongoDB是什么

基于分布式文件存储的一种数据库

MongoDB中的记录是一个文档,它是由字段和值对组成的数据结构。MongoDB文档类似于JSON对象。字段的值可以包括其他文档,数组和文档数组。

6jPs76.png

!> 和mysql对比理解

MongoDB Mysql
DB
collection集合
Document (Json)
fild(Json中的key) 字段
index 索引
数据类型 描述
String 常用类型。在 MongoDB 中,合法编码是UTF-8
Integer 由服务器决定是32 位还是64 位
Boolean 布尔值
Double 双精度浮点值。
Min/Max keys 将一个值与 BSON(二进制的 JSON)元素的最低值和最高值相对比。
Array 用于将数组或列表或多个值存储为一个键。
Timestamp 保存文档修改或添加的时间。
Object 用于内嵌文档。
Null 用于创建空值。
Symbol 符号。该数据类型基本上等同于字符串类型,但不同的是,它一般用于采用特殊符号类型的语言。
Date 保存当前日期或时间。也可自定义 Date 对象。
Object ID 对象 ID。用于创建文档的 ID。
Binary Data 存储二进制数据。
Code 用于在文档中存储 Js 代码。
Regular expression 正则表达式

MongoDB的一些优点

复制高可用性(主从复制,主机读写,从机只读),把数据同步复制到多个服务器中。

分片技术,由于一台服务器不能存储海量数据,所以要把大数据分割开来,然后把分片分布存储在各个服务器中,达到高吞吐量

MongoDB还提供专门的性能监控功能。

MongoDB 的文档数据模型和索引系统能有效提升数据库性能;复制集功能提供数据冗余,自动化容灾容错,提升数据库可用性;分片技术能够分散单服务器的读写压力,提高并发能力,提升数据库的可拓展性。

MongoDB应用场景

  • Mongo非常适合实时的插入,更新与查询,并具备网站实时数据存储所需的复制及高度伸缩性

  • 地理位置信息存储,通过2d和2dsphere索引,可以方便的查询出具体的位置信息

  • 聚合操作处理数据(如统计平均值,求和等),并返回计算结果

MongoDB安装配置和启动(windows下)

1、Mongodb安装包下载

2、下载完安装时有一个“complete”和“custom”选项。 因complete不能选择安装位置,所以我们选择custom安装。

3、在安装根目录下新建data文件夹,data文件夹下再新建一个db和log文件夹。

4、同样在根目录下新建配置文件mongod.cfg,内容如下(注意替换成自己的路径)
systemLog:
destination: file
path: D:\Mongodb\data\log\mongod.log
storage:
dbPath: D:\Mongodb\data\db

5、右键“以管理员身份运行”cmd,输入下面命令,把MongoDB安装为服务(注意自行替换路径)
D:\Mongodb\bin\mongod.exe --config "D:\Mongodb\mongod.cfg" --install

6、运行net start MongoDB启动服务,其它相关服务命令如下(注意自行替换路径)

  • 启动服务:net start MongoDB

  • 关闭服务:net stop MongoDB

  • 移除服务:D:\Mongodb\bin\mongod.exe --remove

7、下载免费的robo3t客户端,解压到文件夹,打开robo3t.exe并连接到localhost:27017。

SpringBoot整合MongoDB

  • 环境准备

!> springboot 2.1.3、jdk 1.8、maven 3.6、MongoDB 3.2.21、Robo 3T 1.4

1、添加spring整合mongodb的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2、配置文件spring.data节点下增加mongodb节点

mongodb:
  host: localhost # ip
  port: 27017 # 端口
  database: mall-port # 库名

3、增加商品浏览记录实体类文档

  • 经测试,字段前加不加@Indexed注解的时候,接口中的findBy...衍生查询都是可以执行,不过查询速度没有加索引的时候快。
  • 实体类可以不用与项目mysql中的表对应,因为这个文档数据是存储在MongoDB中的
@Document //代表MongoDB的集合
public class MemberReadHistory {
    @Id  //MongoDB默认的_id主键
  private String id;
    @Indexed
  private Long memberId;
    private String memberNickname;
    private String memberIcon;
    @Indexed
  private Long productId;
    private String productName;
    private String productPic;
    private String productSubTitle;
    private String productPrice;
    private Date createTime;
    ...get/set方法
    }

4、编写MemberReadHistoryRepository接口继承MongoRepository<T,ID>,可根据规则定义衍生方法,还可以调用CrudRepository<T, ID>接口中封装好的CRUD接口。

public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory,String> {
    /**
 * 根据会员id按时间倒序获取浏览记录
  * @param memberId 会员id
 */  List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);

    List<MemberReadHistory> findByProductName(String pName);
}

5、编写Service层接口

public interface MemberReadHistoryService {
    /**
 * 生成浏览记录(插入MongoDB数据库)
  */
  int create(MemberReadHistory memberReadHistory);

    /**
 * 批量删除浏览记录
  */
  int delete(List<String> ids);

    /**
 * 获取用户浏览历史记录
  */
  List<MemberReadHistory> list(Long memberId);
}

6、Service层实现类Impl(写业务逻辑)

@Service public class MemberReadHistoryServiceImpl implements MemberReadHistoryService {
    @Autowired
  private MemberReadHistoryRepository memberReadHistoryRepository;
    @Override
  public int create(MemberReadHistory memberReadHistory) {
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        memberReadHistoryRepository.save(memberReadHistory);
        return 1;
    }

    @Override
  public int delete(List<String> ids) {
        List<MemberReadHistory> deleteList = new ArrayList<>();
        for(String id:ids){
            MemberReadHistory memberReadHistory = new MemberReadHistory();
            memberReadHistory.setId(id);
            deleteList.add(memberReadHistory);
        }
        memberReadHistoryRepository.deleteAll(deleteList);
        return ids.size();
    }

    @Override
  public List<MemberReadHistory> list(Long memberId) {
        return memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(memberId);
    }
}

7、Controller视图层

@Controller @Api(tags = "MemberReadHistoryController", description = "会员商品浏览记录管理")
@RequestMapping("/member/readHistory")
public class MemberReadHistoryController {
    @Autowired
  private MemberReadHistoryService memberReadHistoryService;
    @Autowired
  private MemberReadHistoryRepository readHistoryRepository;

    @ApiOperation("创建浏览记录")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
  public CommonResult create(@RequestBody MemberReadHistory memberReadHistory) {
        int count = memberReadHistoryService.create(memberReadHistory);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("删除浏览记录")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
  public CommonResult delete(@RequestParam("ids") List<String> ids) {
        int count = memberReadHistoryService.delete(ids);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("展示浏览记录")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
  public CommonResult<List<MemberReadHistory>> list(Long memberId) {
        List<MemberReadHistory> memberReadHistoryList = memberReadHistoryService.list(memberId);
        return CommonResult.success(memberReadHistoryList);
    }
}
posted @ 2025-03-20 15:24  Mosey  阅读(32)  评论(0)    收藏  举报
TOP