Redis 作为唯一的原子 ID 生成器 - Web 应用程序的线程安全方式,以避免竞争条件 [英] Redis as unique atomic id generator - Thread safe way for web app to avoid race condition

查看:86
本文介绍了Redis 作为唯一的原子 ID 生成器 - Web 应用程序的线程安全方式,以避免竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划使用 redis 作为唯一的原子 ID 生成器.但是,我担心可能会有来自多个浏览器的模拟 Web 请求.我想知道,使以下操作原子化的常见做法是什么?

I plan to use redis as an unique atomic id generator. However, my concern there might be simulatoneous web requests from multiple browsers. I was wondering, what is the common practice to make the following operations atomic?

get id from redis
if id is not found
    insert id as 0 into redis
else
    store the id in a variable
    increase id by one
    store the new id back to redis

如果我使用的是桌面应用或移动应用,我会在 Java 中使用 synchronized 关键字来避免 竞争条件.

If I were in desktop app or mobile app, I would use synchronized keyword in Java to avoid race condition.

但是,对于 PHP 网络应用程序呢?

However, how about for a PHP web app?

推荐答案

假设您要生成顺序 ID,您可以使用 Redis 和 INCR 命令而不必担心竞争条件.由于 Redis(大部分)是单线程的,因此您可以放心,每个请求都会从中获得自己的唯一 ID.

Assuming you're looking to generate sequential ids, you can use Redis and the INCR command without worrying about race conditions. Since Redis is (mostly) single threaded, you are assured that every request will get it's own unique id from it.

此外,您不需要检查 id 键的存在/初始化它,因为 Redis 会为您做这件事(即,如果您 INCR 一个不存在的键,它将首先创建并自动设置为 0).

Furthermore, you don't need to check the id key's existence/initialize it because Redis will do that for you (i.e. if you INCR a non-existent key, it will be first created and set to 0 automatically).

这篇关于Redis 作为唯一的原子 ID 生成器 - Web 应用程序的线程安全方式,以避免竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆