search
HomeBackend DevelopmentPHP TutorialScenarios where Redis needs to be used in PHP projects

Redis is an open source log-type Key-Value database written in ANSI C language, supports network, can be memory-based and persistent, and provides APIs in multiple languages. Today we will take a look at some application scenarios of PHP combined with redis. I hope it will be helpful to everyone.

Preface

In some cases, some students said why the string type cannot be used. The string type can be implemented completely

I suggest Please take a look at my column "Advanced Usage of Redis", which introduces the benefits of using hash types

Counting product dimensions

For products Count the number of likes, number of comments, number of appraisals, and number of views
Speaking of e-commerce, products are definitely inseparable, and incidental products have various counts (number of likes, number of comments, number of appraisals, number of views, etc.)
Redis commands are all atomic, you can easily use INCR, DECR and other commands to count.

Use the Redis type: Hash. If you are not familiar with the redis data type, you can refer to
http://redis.io/topics/data-types-intro

Product defines a key product:, and defines a hashkey for each value, such as the number of likes like_num

$redis->hSet('product:123', 'like_num ', 5); // 添加 id为123的商品 like_num 为5
 
$redis->hIncrBy('product:123', 'like_num ', 1); // 添加 id为123的商品like_num +1

$redis->hGetAll('product:123'); // 获取id为123的商品相关信息
                  array('like_num '=> 1)

User dimension count

The number of user dynamics and number of followers , number of fans, number of liked products, number of posts, etc.
User dimension counting and product dimension counting both use Hash. Define a key for User: user:
Define a hashkey for each value, such as the number of followers follow


$redis->hSet('user:100000', 'follow ', 5); // 添加uid为10000的用户follow 为5
 
$redis->hIncrBy('user:100000', 'follow ', 1); // 更新uid为10000的用户follow +1

$redis->hGetAll('user:100000'); // 获取uid为10000的用户
                  array('like_num '=> 1)

                                                                                                                                                                                                                                                 since In a sorted set, score can be timestamp
The default set is sorted in ascending order by scoreIn this way, to find the common friends of two people, you may only need to use the intersection command


$redis->zAdd('user:1000:follow', 1463557212, '1001'); 

                #uid为1000用户关注uid为1001 , score值设定时间戳1463557212

$redis->zAdd('user:1000:follow', 1463557333, '1002'); 

$redis->zAdd('user:2000:follow', 1463577568, '1001'); 

$redis->zAdd('user:2000:follow', 1463896964, '1003');
 
                #uid为2000用户关注1001和1003用户 , score值设定时间戳

$redis->zInter('com_fllow:1000:2000', array('user:1000:follow', 'user:2000:follow')); 

    #对集合'user:1000:follow'和'user:2000:follow'取交集'com_fllow:1000:2000'
    #获得共同关注的uid 

$redis->zRange('com_fllow:1000:2000',0,-1); // 获取全部集合元素
    #array('10001','10002')


Used as cache instead of memcached


Apply to product list, comment list, @tip list

Relatively simple to memcached In terms of key-value storage, redis' numerous data structures (list, set, sorted set, hash, etc)

can more conveniently cache various business data, and the performance is no less than memcached.

NOTE: RPUSH pagewviews.user: EXPIRE pagewviews.user: 60 //Pay attention to update timeout


Anti-spam system



Application Spam control for system comments, product postings, and forum postings

As an e-commerce website, it is inevitable to be attacked by various spam (spam comments, posting spam products, advertisements, brushing your own product rankings, etc.)
Develop a series of anti-spam rules for these spams, some of which can use redis for real-time analysis

For example: no more than 2 comments in 1 minute, less than 5 comments in 5 minutes, etc. (more Mechanism/rules need to be combined with drools)

Conventional sorted set records user operations in the last day

(Why not record all? Save memory, all operations will be recorded in the log, and then use hadoop for more comprehensive analysis and statistics)

#获取5秒内操作记录
$res = $redis->zRangeByScore('user:1000:comment', time() - 5, time());
#判断5秒内不能评论
if (!$res) {
  $redis->zAdd('user:1000:comment', time(), '评论内容');
} else {
  echo '5秒之内不能评论';
}

#5秒内评论不得超过2次
if($redis->zRangeByScore('user:1000:comment',time()-5 ,time())==1)
echo '5秒之内不能评论2次';

#5秒内评论不得少于2次

if(count($redis->zRangeByScore(&#39;user:1000:comment&#39;,time()-5 ,time()))<2)
echo &#39;5秒之内不能评论2次&#39;;

User Timeline/Feeds



Apply to people, topics, brands and columns of concern

redis is mainly used as a cache here

$redis->zAdd(&#39;user:2000:feed:topic&#39;, time(), &#39;13&#39;);
//score 为timestamp uid为2000的用户关注tid为13的topic

$redis->expire(&#39;user:2000:feed:topic&#39;,24*60*60);
#关注有效期为24小时
# ttl 30天之内按秒数计算 30天之外以timestamp为准

Latest List & Ranking


Used to record the latest list or ranking of products that the user has just liked, etc. Business scenario

Latest list of products-sorted set structure presentation

    $redis->zAdd(&#39;user:1000:product:like&#39;, time(), &#39;3002&#39;);
    $redis->zAdd(&#39;user:1000:product:like&#39;, time(), &#39;3001&#39;);
    $redis->zAdd(&#39;user:1000:product:like&#39;, time(), &#39;3004&#39;);
    $redis->zAdd(&#39;user:1000:product:like&#39;, time(), &#39;3003&#39;);
    
    $redis->zRange(&#39;user:1000:product:like&#39;, 0, -1,true); 
    #默认喜欢时间升序序排列
    #
      Array(
        [3002] => 1463565179
        [3001] => 1463565189
        [3004] => 1463565199
        [3003] => 1463565209
      )
    
    $redis->zRevRange(&#39;user:1000:product:like&#39;, 0, -1,true); 
    #以喜欢时间降序排列
    #
      Array
      (
        [3003] => 1463565424
        [3004] => 1463565414
        [3001] => 1463565404
        [3002] => 1463565394
      )
Ranking list-list data structure presentation

    $redis->lPush(&#39;user:1000:product:like&#39;, &#39;3002&#39;);
    $redis->lPush(&#39;user:1000:product:like&#39;, &#39;3001&#39;);
    $redis->lPush(&#39;user:1000:product:like&#39;, &#39;3004&#39;);
    $redis->lPush(&#39;user:1000:product:like&#39;, &#39;3003&#39;);
    
    $redis->lRange(&#39;user:1000:product:like&#39;, 0, -1);
    
    Array
    (
      [0] => 3003
      [1] => 3004
      [2] => 3001
      [3] => 3002
    )

Message notification

Use Hash structure to count message notification business scenarios

$redis->hSet(&#39;user:1000:message:notice&#39;, &#39;system&#39;, 1);
#设置1条未读系统消息

$redis->hIncrBy(&#39;user:1000:message:notice&#39;, &#39;system&#39;, 1);
#未读系统消息+1

$redis->hSet(&#39;user:1000:message:notice&#39;, &#39;comment&#39;, 1);
#设置1条未读评论

$redis->hIncrBy(&#39;user:1000:message:notice&#39;, &#39;comment&#39;, 1);
#未读评论+1

$redis->hGetAll(&#39;user:1000:message:notice&#39;);
#查看所有消息通知数量

Array
(
  [system] => 2
  [comment] => 2
)

Use Redis as a message queue

Use Redis’s List data structure to achieve distribution Message queue

Related recommendations:

PHP Redis extension from installation to use

PHP uses redis to realize session instance sharing

phalapi-cache usage and redis expansion

The above is the detailed content of Scenarios where Redis needs to be used in PHP projects. For more information, please follow other related articles on the PHP Chinese website!

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools