在 EggJS 中实现 Redis 上锁

配置环境

下载 Redis

Windows

访问 https://github.com/microsoftarchive/redis/releases 选择版本进行下载 - 勾选 [配置到环境变量] - 无脑下一步并安装

在这里插入图片描述

命令行执行:redis-cli -v 查看已安装的 Redis 版本,能成功查看就表示安装成功啦~


Mac

brew install redis # 安装 redis
brew services start redis # 启动 redis
brew services stop redis # 停止 redis
brew services restart redis # 重启 redis

启动 Redis

打开任务管理器,找到 Redis 服务,点击启动即可

在这里插入图片描述



配置 EggJS 项目

  1. 安装依赖
pnpm i egg-redis

  1. 配置插件
// config/plugin.js
exports.redis = {
    enable: true,
    package: 'egg-redis',
};
// config/config.default.js
exports.redis = {
    client: {
        port: 6379, // Redis port
        host: '127.0.0.1', // Redis host
        password: '',
        db: 0,
    },
};

  1. 扩展 helper
// app/extend/helper.js
module.exports = {
    // 生成 redis 锁的控制器; val 为随机数, 防止解锁时误删其他请求的锁
    redisLockController(key, val = Math.random(), ttl = 5 * 60) {
        const app = this.app;
        return {
            // 上锁
            async lock() {
                // 使用 set 命令上锁并设置过期时间, 保证原子性
                const lockResult = await app.redis.set(
                    key,
                    val,
                    'EX',
                    ttl,
                    'NX'
                );
                return lockResult === 'OK';
            },
            // 解锁
            async unlock() {
                // 使用 lua 脚本校验锁并解锁, 保证原子性
                const script = `
					if redis.call('get', KEYS[1]) == ARGV[1] then
						return redis.call('del', KEYS[1])
					else
						return 0
					end
				`;
                // 使用 eval 命令执行 lua 脚本
                const unlockResult = await app.redis.eval(script, 1, key, val);
                return unlockResult === 1;
            },
        };
    },
};

  1. 使用 redis 上锁
// app/controller/home.js
const { Controller } = require('egg');

module.exports = class HomeController extends Controller {
    async index() {
        const { id = 0 } = this.ctx.query;
        const result = await this.service.home.index(id);
        this.ctx.body = result;
    }
};
// app/service/home.js
const { Service } = require('egg');

module.exports = class HomeService extends Service {
    async index(id) {
        // 从 header 中获取 region 参数
        const region = this.ctx.get('region') || 'default';
        // 生成锁的 key
        const lockKey = `lock:${region}:${id}`;
        // 获取锁的控制器
        const { lock, unlock } = this.ctx.helper.redisLockController(lockKey);
        // 上锁
        const lockResult = await lock();
        // 上锁失败
        if (!lockResult) return { code: 500, msg: 'lock failed' };
        // 上锁成功, 执行业务逻辑
        let result;
        try {
            const sqlResult = await this.mockSql(id);
            result = { code: 200, msg: 'success', data: sqlResult };
        } catch (err) {
            this.ctx.logger.error(err);
            result = { code: 500, msg: err.message };
        }
        // 解锁
        await unlock();
        // 返回结果
        return result;
    }

    // 模拟数据库查询
    async mockSql(id) {
        // 2s 后返回结果
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve({ id, time: Date.now() });
            }, 2000);
        });
    }
};

Multi Clients

// config/config.default.js
exports.redis = {
    clients: {
        // 配置各个 client
        instance: {
            port: 6379,
            host: '127.0.0.1',
            password: '',
            db: 0,
        },
        // ...
    },
};
// app/extend/helper.js
module.exports = {
    redisLockController(key, val = Math.random().toFixed(6), ttl = 5 * 60) {
        const app = this.app;
        return {
            // 上锁
            async lock() {
                // 使用指定 client
                const lockResult = await app.redis
                    .get('instance')
                    .set(key, val, 'EX', ttl, 'NX');
                return lockResult === 'OK';
            },
            // 解锁
            async unlock() {
                const script = `
					if redis.call('get', KEYS[1]) == ARGV[1] then
						return redis.call('del', KEYS[1])
					else
						return 0
					end
				`;
                // 使用指定 client
                const unlockResult = await app.redis
                    .get('instance')
                    .eval(script, 1, key, val);
                return unlockResult === 1;
            },
        };
    },
};



模拟抢锁

开两个浏览器访问 http://localhost:7001 即可模拟抢锁的场景


  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JS.Huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值