search
Homephp教程php手册基于memcached的php锁机制实现

基于memcached的php锁机制实现

Jun 06, 2016 pm 07:57 PM
benmemcachedphpbased onaccomplishmechanism

PHP处理大规模并发,特别是恶意辅助工具发送恶意请求的情况下,这时候就需要用到锁机制。 常备恶意请求的接口一般都会操作db,如果db不支持事务或者db和PHP之间有第三方插件的话,很容易出现多个php接口返回成功的现象。 php有一种基于文件的锁机制,fblock

PHP处理大规模并发,特别是恶意辅助工具发送恶意请求的情况下,这时候就需要用到锁机制。

常备恶意请求的接口一般都会操作db,如果db不支持事务或者db和PHP之间有第三方插件的话,很容易出现多个php接口返回成功的现象。

php有一种基于文件的锁机制,fblock,但是对于有很多web机的应用,php接口会负载均衡到所有的web机,只能做对同一台web机的锁机制,并且非常耗资源。

现在的锁机制就需要一个全局可以访问可写的变量。
此时有两种选择,数据库,memcached。

为了减轻负担,使用memcached。  


锁定方法: memcached并没有提供锁定某一个key的方法,可以通过其他方法来实现锁定。最常用的是用add方法。例如,我们要更新一个key,可以先王 memcached里面add一个叫lock_key的键值,如果add成功,就说明锁定上了,否则,说明memcached里面已经有lock_key 这个键值,有其他程序在锁定这个key了


实现php自由锁:

1加锁(设置memcached的最大过期时间,比如5s,避免加锁后忘记解锁)

addmemcached

2解锁

detele


使用apache自带的压力测试工具 

./ab -n1000 -c100 http://*****

每秒钟一千个请求,一百个并发,锁机制工作正常。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!