夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Node基础

  • 《MySQL》学习笔记

  • Midway

  • Nest

    • 开篇词
    • 学习理由
    • nest概念扫盲
    • 快速掌握 nestcli
    • 5种http数据传输方式
    • IoC 解决了什么痛点问题?
    • 如何调试 Nest 项目
    • Provider注入对象
    • 全局模块和生命周期
    • AOP 架构有什么好处?
    • 一网打尽 Nest 全部装饰器
    • Nest如何自定义装饰器
    • Metadata和Reflector
    • ExecutionContext切换上下文
    • Module和Provider的循环依赖处理
    • 如何创建动态模块
    • Nest和Express,fastify
    • Nest的Middleware
    • RxJS和Interceptor
    • 内置Pipe和自定义Pipe
    • ValidationPipe验证post请求参数
    • 如何自定义 Exception Filter
    • 图解串一串 Nest 核心概念
    • 接口如何实现多版本共存
    • Express如何使用multer实现文件上传
    • Nest使用multer实现文件上传
    • 图书管理系统
    • 大文件分片上传
    • 最完美的 OSS 上传方案
    • Nest里如何打印日志
    • 为什么Node里要用Winston打印日志
    • Nest 集成日志框架 Winston
    • 通过Desktop学Docker也太简单了
    • 你的第一个 Dockerfile
    • Nest 项目如何编写 Dockerfile
    • 提升 Dockerfile 水平的 5 个技巧
    • Docker 是怎么实现的
    • 为什么 Node 应用要用 PM2 来跑?
    • 快速入门 MySQL
    • SQL 查询语句的所有语法和函数
    • 一对一、join 查询、级联方式
    • 一对多、多对多关系的表设计
    • 子查询和 EXISTS
    • SQL 综合练习
    • MySQL 的事务和隔离级别
    • MySQL 的视图、存储过程和函数
    • Node 操作 MySQL 的两种方式
    • 快速掌握 TypeORM
    • TypeORM 一对一的映射和关联 CRUD
    • TypeORM 一对多的映射和关联 CRUD
    • TypeORM 多对多的映射和关联 CRUD
    • 在 Nest 里集成 TypeORM
    • TypeORM保存任意层级的关系
    • 生产环境为什么用TypeORM的migration迁移功能
    • Nest 项目里如何使用 TypeORM 迁移
    • 如何动态读取不同环境的配置?
    • 快速入门 Redis
    • 在 Nest 里操作 Redis
    • 为什么不用 cache-manager 操作 Redis
    • 两种登录状态保存方式:JWT、Session
    • Nest 里实现 Session 和 JWT
    • MySQL + TypeORM + JWT 实现登录注册
    • 基于 ACL 实现权限控制
    • 基于 RBAC 实现权限控制
    • access_token和refresh_token实现无感登录
    • 单token无限续期实现登录无感刷新
    • 使用 passport 做身份认证
    • passport 实现 GitHub 三方账号登录
    • passport 实现 Google 三方账号登录
    • 为什么要使用 Docker Compose ?
    • Docker 容器通信的最简单方式:桥接网络
    • Docker 支持重启策略,是否还需要 PM2
    • 快速掌握 Nginx 的 2 大核心用法
    • 基于 Nginx 实现灰度系统
    • 基于 Redis 实现分布式 session
    • Redis + 高德地图,实现附近的充电宝
    • 用 Swagger 自动生成 api 文档
    • 如何灵活创建 DTO
    • class- validator 的内置装饰器,如何自定义装饰器
    • 序列化 Entity,你不需要 VO 对象
    • 手写序列化 Entity 的拦截器
    • 使用 compodoc 生成文档
    • Node 如何发邮件?
    • 实现基于邮箱验证码的登录
    • 基于 sharp 实现 gif 压缩工具
    • 大文件如何实现流式下载?
    • Puppeteer 实现爬虫,爬取 BOSS 直聘全部前端岗位
    • 实现扫二维码登录
    • Nest 的 REPL 模式
    • 实现 Excel 导入导出
    • 如何用代码动态生成 PPT
    • 如何拿到服务器 CPU、内存、磁盘状态
    • Nest 如何实现国际化?
    • 会议室预订系统:需求分析和原型图
    • 会议室预订系统:技术方案和数据库设计
    • 会议室预订系统:用户管理模块--用户注册
    • 会议室预订系统:用户管理模块--配置抽离、登录认证鉴权
    • 会议室预订系统:用户管理模块-- interceptor、修改信息接口
    • 会议室预订系统:用户管理模块--用户列表和分页查询
    • 会议室预订系统:用户管理模块-- swagger 接口文档
    • 会议室预订系统:用户管理模块-- 用户端登录注册页面
    • 会议室预订系统:用户管理模块-- 用户端信息修改页面
    • 会议室预订系统:用户管理模块-- 头像上传
    • 会议室预订系统:用户管理模块-- 管理端用户列表页面
    • 会议室预订系统:用户管理模块-- 管理端信息修改页面
    • 会议室预订系统:会议室管理模块-后端开发
    • 会议室预订系统:会议室管理模块-管理端前端开发
    • 会议室预订系统:会议室管理模块-用户端前端开发
    • 会议室预订系统:预定管理模块-后端开发
    • 会议室预订系统:预定管理模块-管理端前端开发
    • 会议室预订系统:预定管理模块-用户端前端开发
    • 会议室预订系统:统计管理模块-后端开发
    • 会议室预订系统:统计管理模块-前端开发
    • 会议室预订系统:后端项目部署到阿里云
    • 会议室预订系统:前端项目部署到阿里云
    • 会议室预定系统:用 migration 初始化表和数据
    • 会议室预定系统:文件上传 OSS
    • 会议室预定系统:Google 账号登录后端开发
    • 会议室预定系统:Google 账号登录前端开发
    • 会议室预定系统:后端代码优化
    • 会议室预定系统:集成日志框架 winston
    • 会议室预定系统:前端代码优化
    • 会议室预定系统:全部功能测试
    • 会议室预定系统:项目总结
    • Nest 如何创建微服务?
    • Nest 的 Monorepo 和 Library
    • 用 Etcd 实现微服务配置中心和注册中心
    • Nest 集成 Etcd 做注册中心、配置中心
    • 用 Nacos 实现微服务配置中心和注册中心
    • 基于 gRPC 实现跨语言的微服务通信
    • 快速入门 ORM 框架 Prisma
    • Prisma 的全部命令
    • Prisma 的全部 schema 语法
    • Primsa Client 单表 CRUD 的全部 api
    • Prisma Client 多表 CRUD 的全部 api
    • 在 Nest 里集成 Prisma
    • 为什么前端监控系统要用 RabbitMQ?
    • 基于 Redis 实现关注关系
      • 总结
    • 基于 Redis 实现各种排行榜(周榜、月榜、年榜)
    • 考试系统:需求分析
    • 考试系统:技术方案和数据库设计
    • 考试系统:微服务、Lib 拆分
    • 考试系统;用户注册
    • 考试系统:用户登录、修改密码
    • 考试系统:考试微服务
    • 考试系统:登录、注册页面
    • 考试系统:修改密码、试卷列表页面
    • 考试系统:新增试卷、回收站
    • 考试系统:试卷编辑器
    • 考试系统:试卷回显、预览、保存
    • 考试系统:答卷微服务
    • 考试系统:答题页面
    • 考试系统:自动判卷
    • 考试系统:分析微服务、排行榜页面
    • 考试系统:整体测试
    • 考试系统:项目总结
    • 用 Node.js 手写 WebSocket 协议
    • Nest 开发 WebSocket 服务
    • 基于 Socket.io 的 room 实现群聊
    • 聊天室:需求分析和原型图
    • 聊天室:技术选型和数据库设计
    • 聊天室:用户注册
    • 聊天室:用户登录
    • 聊天室:修改密码、修改信息
    • 聊天室:好友列表、发送好友申请
    • 聊天室:创建聊天室、加入群聊
    • 聊天室:登录、注册页面开发
    • 聊天室:修改密码、信息页面开发
    • 聊天室:头像上传
    • 聊天室:好友∕群聊列表页面
    • 聊天室:添加好友弹窗、通知页面
    • 聊天室:聊天功能后端开发
    • 聊天室:聊天功能前端开发
    • 聊天室:一对一聊天
    • 聊天室:创建群聊、进入群聊
    • 聊天室:发送表情、图片、文件
    • 聊天室:收藏
    • 聊天室:全部功能测试
    • 聊天室:项目总结
    • MongoDB 快速入门
    • 使用 mongoose 操作 MongoDB 数据库
    • GraphQL 快速入门
    • Nest 开发 GraphQL 服务:实现 CRUD
    • GraphQL + Primsa + React 实现 TodoList
    • 如何调试 Nest 源码?
  • 其他

  • 服务端
  • Nest
神说要有光
2025-03-10
目录

基于 Redis 实现关注关系

在掘金、知乎、抖音等平台,我们可以关注其他用户,其他用户也可以关注我们,而且如果彼此关注,会标出共同关注:

这种关注、被关注,相互关注,我们每天都能见到。

那它是怎么实现的呢?

一般是用 redis 的 Set 实现的。

Set 是集合,有很多命令:

SADD:添加元素

SMEMBERS:查看所有元素

SISMEMBER:某个 key 是否在集合中

SCARD:集合中某个 key 的元素数量

SMOVE:移动元素从一个集合到另一个集合

SDIFF:两个集合的差集

SINTER:两个集合的交集

SUNION:两个集合的并集

SINTERSTORE:两个集合的交集,存入新集合

SUNIONSTORE:两个集合的并集,存入新集合

SDIFFSTORE:两个集合的差集,存入新集合

更多命令可以在 redis 文档 (opens new window)中搜索以 S 开头的:

关注关系用 redis 来实现就是这样的:

比如张三 的 userId 是 1

那我们用一个 set 来存储它的关注者 followers:1

比如其中有 2、3、4 三个用户

然后用一个集合来存储他关注的人 following:1

其中有 2、5、6 三个用户

那相互关注的人就是 followers:1 和 following:1 的交集 SINTERSTORE 的结果,存入新集合,比如叫 follow-each-other:1

然后返回关注者或者关注的人的时候,用 SISMEMBER 判断下用户是否在 follow-each-other:1 这个集合中,是的话就可以标记出互相关注。

思路理清了,我们来写下代码。

安装 TypeORM 的包:

npm install --save @nestjs/typeorm typeorm mysql2
1

在 app.module.ts 引入下 TypeOrmModule:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: "mysql",
      host: "localhost",
      port: 3306,
      username: "root",
      password: "guang",
      database: "following_test",
      synchronize: true,
      logging: true,
      entities: [],
      poolSize: 10,
      connectorPackage: 'mysql2',
      extra: {
          authPlugin: 'sha256_password',
      }
    })
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
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

在 mysql workbench 里创建 following_test 数据库:

新建一个 user 模块:

nest g resource user --no-spec
1

改下 user.entity.ts

import { Column, Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => User, user => user.following)
    @JoinTable()
    followers: User[];

    @ManyToMany(() => User, user => user.followers)
    following: User[];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

这里用户和用户是多对多的关系,因为用户可以关注多个用户,用户也可以被多个用户关注。

所以用 @ManyToMany 还有 @JoinTable 来声明。

在 entities 引入这个 User:

把开发服务跑起来:

npm run start:dev
1

在 mysql workbench 里可以看到 user 表和 user_followers_user 中间表

我们在 UserService 添加一个初始化数据的方法:

@InjectEntityManager()
entityManager: EntityManager;

async initData() {    
    const user2 = new User();
    user2.name = '李四';

    const user3 = new User();
    user3.name = '王五';

    const user4 = new User();
    user4.name = '赵六';

    const user5 = new User();
    user5.name = '刘七';

    await this.entityManager.save(user2);
    await this.entityManager.save(user3);
    await this.entityManager.save(user4);
    await this.entityManager.save(user5);

    const user1 = new User();
    user1.name = '张三';

    user1.followers = [user2, user3, user4];

    user1.following = [user2, user5];

    await this.entityManager.save(user1);
}
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

在 UserController 里添加一个路由:

@Get('init')
async init() {
    await this.userService.initData();
    return 'done'
}
1
2
3
4
5

浏览器访问下:

打印了 6 条 sql 语句:

在 mysql workbench 里看下:

张三的 id 是 5,他的三个关注者李四、王五、赵六,他关注的人李四、刘七。

关系都保存下来了。

接下来实现相互关注功能,我们要引入 redis。

安装 redis 的包:

npm install --save redis
1

然后创建个 redis 模块:

nest g module redis
nest g service redis
1
2

在 RedisModule 创建连接 redis 的 provider,导出 RedisService,并把这个模块标记为 @Global 模块

import { Global, Module } from '@nestjs/common';
import { createClient } from 'redis';
import { RedisService } from './redis.service';

@Global()
@Module({
  providers: [
    RedisService,
    {
      provide: 'REDIS_CLIENT',
      async useFactory() {
        const client = createClient({
            socket: {
                host: 'localhost',
                port: 6379
            }
        });
        await client.connect();
        return client;
      }
    }
  ],
  exports: [RedisService]
})
export class RedisModule {}
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

然后在 RedisService 里注入 REDIS_CLIENT,并封装一些方法:

import { Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from 'redis';

@Injectable()
export class RedisService {

    @Inject('REDIS_CLIENT') 
    private redisClient: RedisClientType;

    async sAdd(key: string, ...members: string[]) {
        return this.redisClient.sAdd(key, members);
    }

    async sInterStore(newSetKey: string, set1: string, set2: string) {
        return this.redisClient.sInterStore(newSetKey, [set1, set2]);
    }

    async sIsMember(key: string, member: string) {
        return this.redisClient.sIsMember(key, member);
    }
    
    async sMember(key: string) {
        return this.redisClient.sMembers(key);
    }
    
    async exists(key: string) {
        const result =  await this.redisClient.exists(key);
        return result > 0
    } 
}
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

封装 SADD、SINTERSTORE、SISMEMBER、SMEMBER 命令,分别用来往集合中添加元素,求两个集合的交集创建新集合,判断元素是否在某个集合中、返回集合中的所有元素。

还有 EXISTS 用来判断某个 key 是否存在,返回 1 代表存在,返回 0 代表不存在。

然后在 UserService 添加一个方法:

@Inject(RedisService)
redisService: RedisService;

async findUserByIds(userIds: string[] | number[]) {
  let users = [];

  for(let i = 0; i< userIds.length; i ++) {
    const user = await this.entityManager.findOne(User, {
      where: {
        id: +userIds[i]
      }
    });
    users.push(user);
  }

  return users;
}

async getFollowRelationship(userId: number) {
  const exists = await this.redisService.exists('followers:' + userId);
  if(!exists) {
    const user = await this.entityManager.findOne(User, {
      where: {
        id: userId
      },
      relations: ['followers', 'following']
    });

    if(!user.followers.length || !user.following.length) {
      return {
        followers: user.followers,
        following: user.following,
        followEachOther: []
      }
    }

    await this.redisService.sAdd('followers:' + userId, ...user.followers.map(item => item.id.toString()));

    await this.redisService.sAdd('following:' + userId, ...user.following.map(item => item.id.toString()))

    await this.redisService.sInterStore('follow-each-other:' + userId, 'followers:' + userId, 'following:' + userId);

    const followEachOtherIds = await this.redisService.sMember('follow-each-other:' + userId);
    
    const followEachOtherUsers = await this.findUserByIds(followEachOtherIds);

    return {
      followers: user.followers,
      following: user.following,
      followEachOther: followEachOtherUsers
    }
  } else {

    const followerIds = await this.redisService.sMember('followers:' + userId);
    
    const followUsers = await this.findUserByIds(followerIds);
    
    const followingIds = await this.redisService.sMember('following:' + userId);
    
    const followingUsers = await this.findUserByIds(followingIds);

    const followEachOtherIds = await this.redisService.sMember('follow-each-other:' + userId);
    
    const followEachOtherUsers =await this.findUserByIds(followEachOtherIds);

    return {
      followers: followUsers,
      following: followingUsers,
      followEachOtherUsers: followEachOtherUsers
    }
  }
}
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

代码比较多,我们一部分一部分的看:

传入 userIds,查询对应的 User 信息返回。

根据 id 查询用户的信息,关联查出 followers 和 following。

如果 follwers 或者 following 为空,那就没有互相关注,可以直接返回。

否则就分别把 follwers 和 follwing 的 id 用 SADD 添加到两个集合中。

之后求两个集合的交集,存入 follow-each-other:userId 的集合。

最后把 followers、following 还有求出来的相互关注的关系返回。

如果 exits 判断 followers 集合存在,就是处理过了,那就直接取 redis 里的这三个集合。

根据集合的 id 求出用户信息返回:

在 UserController 添加一个路由:

@Get('follow-relationship')
async followRelationShip(@Query('id') id: string) {
    if(!id) {
      throw new BadRequestException('userId 不能为空');
    }
    return this.userService.getFollowRelationship(+id);
}
1
2
3
4
5
6
7

浏览器访问下:

结果是正确的。

在 RedisInsight 里可以看到这三个 set:

逻辑比较复杂,我们调试下。

点击 debug 面板的 create a launch.json file

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "debug nest",
            "request": "launch",
            "runtimeArgs": [
                "run",
                "start:dev"
            ],
            "runtimeExecutable": "npm",
            "console": "integratedTerminal",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "node"
        }
    ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

在代码里打两个断点:

点击 debug 启动:

浏览器访问下:

可以看到,它走到了 else 部分。

在 RedisInsight 里把这三个集合删掉:

再次访问:

这时候走的就是另一个分支了。

那如果有新的关注者呢?

比如张三又关注了 id 为 3 的赵六:

这时要更新下数据库,并且更新 redis 里的 follwing 和 follow-each-other 集合。

在 UserService 添加 follow 方法:

async follow(userId: number, userId2: number){
  const user = await this.entityManager.findOne(User, {
    where: {
      id: userId
    },
    relations: ['followers', 'following']
  });

  const user2 = await this.entityManager.findOne(User, {
    where: {
      id: userId2
    }
  });

  user.followers.push(user2);

  await this.entityManager.save(User, user);

  const exists = await this.redisService.exists('followers:' + userId);

  if(exists) {
    await this.redisService.sAdd('followers:' + userId, userId2.toString());
    await this.redisService.sInterStore('follow-each-other:' + userId, 'followers:' + userId, 'following:' + userId);
  }
  
 const exists2 = await this.redisService.exists('following:' + userId2);

 if(exists2) {
    await this.redisService.sAdd('following:' + userId2, userId.toString());
    await this.redisService.sInterStore('follow-each-other:' + userId2, 'followers:' + userId2, 'following:' + userId2);
  }
}
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

先查询出 user 的数据,在 followers 添加 user2,然后 save 保存到数据库。

之后查询下 redis,如果有 followers:userId 的 key,就更新下 followers 和 follow-each-other 集合。

这里 user1 和 user2 的集合都要查询并更新下。

然后在 UserController 里添加下路由:

@Get('follow')
async follow(@Query('id1') userId1: string, @Query('id2') userId2: string) {
    await this.userService.follow(+userId1, +userId2);
    return 'done';
}
1
2
3
4
5

浏览器访问下:

可以看到,数据库和 redis 都更新了:

再次查询下:

这样,相互关注的功能就实现了。

知乎、掘金这种关注关系都是这样实现的:

案例代码上传了小册仓库 (opens new window)

# 总结

这节我们实现了下关注、被关注、互相关注。

在 mysql 里用中间表来存储 user 和 user 的关系,在 TypeORM 里用 @ManyToMany 映射。

互相关注用 redis 的 Set 来实现,先把 user 的 followers 和 following 存储到集合中。

然后把两个集合的交集求出来放入一个新的集合。

这样就能求出互相关注的关系。

当有新的关注或者取消关注时,除了要更新数据库外,也要顺便更新下 redis。

这样,查询互相关注关系的功能就完成了。

编辑 (opens new window)
上次更新: 2025/10/27 10:53:52
为什么前端监控系统要用 RabbitMQ?
基于 Redis 实现各种排行榜(周榜、月榜、年榜)

← 为什么前端监控系统要用 RabbitMQ? 基于 Redis 实现各种排行榜(周榜、月榜、年榜)→

最近更新
01
H5调用微信jssdk
09-28
02
VueVirtualScroller
09-19
03
如何调试 Nest 项目
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式