当前位置:网站首页>PHP uses redis transaction to realize commodity spike
PHP uses redis transaction to realize commodity spike
2022-07-22 11:47:00 【It dongdongge】
One 、 Business
1、 Open transaction multi
2、 Perform transactions exec
3、 Discard transaction discard
notes : The following two cases ,
a. If there is an error in a command during the execution of the transaction queue , The entire transaction command queue will be discarded
b. There is no error in joining the queue , An error is reported when executing a command , Other commands will be executed successfully .( Non atomicity )
Two 、 Pessimistic lock and optimistic lock
1、 Pessimistic locking
Pessimistic locking (Pessimistic Lock), seeing the name of a thing one thinks of its function , Is very pessimistic , Every time I go to get the data, I think others will modify it , So every time I get the data, I lock it , So that if people want to take this data, they will block Until it gets the lock . There are many lock mechanisms used in traditional relational databases , For example, line locks. , Table lock, etc. , Read the lock , Write locks, etc. , It's all locked before the operation .
2、 Optimism lock
Optimism lock (Optimistic Lock), seeing the name of a thing one thinks of its function , Is very optimistic , Every time I go to get the data, I think other people won't modify it , So it won't lock , But in the process of updating, we will judge whether other people have updated this data during this period , You can use mechanisms like version numbers . Optimistic lock is suitable for multi read applications , This can improve throughput .Redis It's using this check-and-set The mechanism implements the .
scene : Grab tickets .
Here's an example : Left client settings sign=10, In execution multi Before , Execute first watch key1 [key2], You can watch one ( Or more ) key, If before the transaction is executed ( Or these ) key Altered by other orders , Then the business will be interrupted .· You can see that the coordinates are set to 20 succeed , Right side setting 30 You don't succeed .
notes :unwatch, Cancel surveillance
3、 ... and 、 utilize redis Realize the second kill function
The code is as follows
<?php
class RedisPool
{
private static $connections = array(); // Define an object pool
private static $servers = array(); // Definition redis The configuration file Contains all the redis The server
public static function addServer($conf) // Definition add redis Configuration method
{
foreach ($conf as $alias => $data){
self::$servers[$alias]=$data;
}
}
public static function getRedis($alias,$select = 0)// Two parameters: the server to be connected KEY, Library to select
{
if(!array_key_exists($alias,self::$connections)){ // Judge whether there is in the connection pool
$redis = new \Redis();
$redis->connect(self::$servers[$alias][0],self::$servers[$alias][1]);
self::$connections[$alias]=$redis;
if(isset(self::$servers[$alias][2]) && self::$servers[$alias][2]!=""){
self::$connections[$alias]->auth(self::$servers[$alias][2]);
}
}
self::$connections[$alias]->select($select);
return self::$connections[$alias];
}
}
function connect_to_redis()
{
// Use redis Connection pool
$conf = array(
'RA' => array('127.0.0.1','6379') // Definition Redis To configure
);
RedisPool::addServer($conf); // add to Redis To configure
$redis = RedisPool::getRedis('RA',1); // Connect RA, Use the default 0 library
return $redis;
}
$user_id = rand(100,999);
$redis = connect_to_redis();
// Monitor inventory
$redis->watch(['goods_num']);
$goods_num = $redis->get('goods_num');
if ($goods_num <= 0){
echo " No stock ";
return 1;
}
// The number
$redis->multi();
$redis->DECR('goods_num', 1);
// Buyers join the queue
$redis->lPush('users', $user_id);
$status = $redis->exec();
// // If it fails, cancel the transaction
if (!$status) {
$redis->discard();
}
Of course, they are all tested in Gaohe
Use ab Pressure measuring tool
ab -n 500 -c 30 http://re.com/re.php
This code solves the following problems :
1、 Oversold -redis Business + Optimism lock + Inventory monitoring
2、redis Connection timeout -redis Connection pool
But there's a problem : When the total number of requests -n Is precisely 50 There was a problem left over from inventory , To solve this problem , We use it LUA Script to achieve
3、 Inventory remaining problems -LUA foot
LUA The script is similar to redis Business , It has certain atomicity , Will not be interrupted by other orders , You can do some redis Transactional operations . But notice redis Of lua Script function , Only in Redis 2.6 The above version can only be used . utilize lua Scripts weed out users , Solve the oversold problem .,
redis 2.6 After the version , adopt lua Scripts solve the scramble problem , It's actually redis Take advantage of its single threaded feature , Using task queue to solve the problem of multitask concurrency ."
<?php
class RedisPool
{
private static $connections = array(); // Define an object pool
private static $servers = array(); // Definition redis The configuration file Contains all the redis The server
public static function addServer($conf) // Definition add redis Configuration method
{
foreach ($conf as $alias => $data){
self::$servers[$alias]=$data;
}
}
public static function getRedis($alias,$select = 0)// Two parameters: the server to be connected KEY, Library to select
{
if(!array_key_exists($alias,self::$connections)){ // Judge whether there is in the connection pool
$redis = new \Redis();
$redis->connect(self::$servers[$alias][0],self::$servers[$alias][1]);
self::$connections[$alias]=$redis;
if(isset(self::$servers[$alias][2]) && self::$servers[$alias][2]!=""){
self::$connections[$alias]->auth(self::$servers[$alias][2]);
}
}
self::$connections[$alias]->select($select);
return self::$connections[$alias];
}
}
function connect_to_redis()
{
// Use redis Connection pool
$conf = array(
'RA' => array('47.95.33.138','6379') // Definition Redis To configure
);
RedisPool::addServer($conf); // add to Redis To configure
$redis = RedisPool::getRedis('RA',1); // Connect RA, Use the default 0 library
return $redis;
}
$user_id = rand(100,999);
$redis = connect_to_redis();$lua = <<<LUA
local num = redis.call("get", 'goods_num')
if tonumber(num)<=0 then
return 0
else
redis.call("decr", 'goods_num')
redis.call("lpush", 'users', KEYS[1])
end
return 1
LUA;$l = <<<LUA
redis.call("lpush", 'users', KEYS[1])
return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}
LUA;
$s = $redis->eval($lua,array($user_id),1);
if ($s == 0){
echo " The second kill is over ";
}else{
echo " Congratulations on the success of secsha ";
}
ab -n 50 -c 30 http://re.com/re.php
This is the second kill , The above code solves several key problems in seckill :redis Connection timeout , Sell less 、 Overbought problem , Of course, there will be other problems in the actual production process , If you encounter a welcome message to discuss .
边栏推荐
- 3 亿
- 伙伴云戴志康:如何利用低代码提升研发和IT效能
- Android 面试题:说一下 PendingIntent 和 Intent 的区别
- Is it safe for flush to open Huatai Securities account?
- J9 number theory: what is Dao? What is the origin of Dao
- [notes d'étude] vous emmène à 01trie à partir de 0
- 多线程与高并发day09
- 深度剖析问题:Could not run ‘torchvision::nms‘ with arguments from the ‘CUDA‘ backend.
- 通过UDP方式点灯
- Paper sharing, target detection, image segmentation, supervised learning, etc
猜你喜欢
ctfhub(rce智慧树)
多線程與高並發day09
“洗钱”
Redis的 缓存穿透、击穿、雪崩
Multithreading and high concurrency day09
Sentinel vs Hystrix 对比,你怎么选?
Tail recursive call process sorting
Ready to use & comparison OPS & pytoch official document summary & Notes (VII)
Pyinstaller packaging & problem solving about enum34 & reduced version
MySQL insert ignore and replace into
随机推荐
马斯克上传大脑很疯狂,Neuralink却早已一地鸡毛
ctfhub(rce智慧树)
Leetcode skimming -- bit by bit record 021
即看即用 && 比较操作(Comparison Ops) && Pytorch官方文档总结 && 笔记 (七)
二分查找/折半查找
基于JSP+Servlet+MySQL+Bootstrap+CSS的图书管理系统
加密市场飙升至1万亿美元以上 不过是假象?加密熊市远未见底
Opencv && 把视频裁剪成指定帧率的图像集
Multithreading et haute concurrence day09
嵌入式分享合集18
Meta:从移动技术发展和创新来预测元宇宙的潜在影响
滴滴被罚80.26亿元,马斯克携芭比娃娃造玩具,DALL-E邀请百万人加入测试,今日更多新鲜事在此
Instant use & other operations & pytoch official document summary & Notes (VIII)
即看即用 && 序列化和并行化 ( Serialization and Parallelism) && Pytorch官方文档总结 && 笔记 (四)
Using virtual to implement hooks in solidity
详解Redis的数据结构
Here comes the multilingual model that everyone can use! It supports 59 languages, parameters 176billion, and is jointly sponsored by 1000 scientists
基于SSM+MySQL+EasyUI+的博客论坛管理系统
J9数字论:什么是 DAO?DAO 的起源是什么
[learning notes] take you to learn 01trie from 0