场景举例:同一用户因为客户端或者网络卡顿,提交评论时,连续点击提交,重复评论相同内容
方法:通过redis分布式锁
<?php
/**
* 幂等检查
* @author weihaoyu
*/
class App_idempotent
{
const KEY_PREFIX = 'IDEMPONTENT::';
protected $redis;
public function __construct()
{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$this->redis = $redis;
}
public function isIdempotent($key, $second = 3)
{
$params = [
'key' => self::KEY_PREFIX . $key,
'value' => 1,
'other' => ['nx', 'ex' => $second],
];
return !$this->redis->setnew($params)['result'];
}
}