Home PHP Framework Workerman How to use Workerman to implement a real-time monitoring system

How to use Workerman to implement a real-time monitoring system

Nov 07, 2023 am 11:00 AM
programming workerman real time monitoring

How to use Workerman to implement a real-time monitoring system

With the rapid development of the Internet and people's increasing demand for real-time monitoring, real-time monitoring systems based on the Web are becoming more and more popular. This article will introduce how to use Workerman to implement a real-time monitoring system. This system can monitor multiple data types as needed, such as logs, performance indicators, machine status, etc. It also provides real-time alarm functions to help administrators grasp the system operating status in a timely manner.

Workerman is a high-performance TCP/UDP server framework written in pure PHP, which has the characteristics of high concurrency, low latency, and easy expansion. Using Workerman, you can easily implement some high-performance, high-concurrency application scenarios, such as long link services, chat rooms, online game servers, etc. Below we will introduce how to use Workerman to implement a real-time monitoring system.

  1. Create a Workerman application

Before using Workerman, you need to download and install the framework. Here we take the Linux environment as an example and use composer to install it. Enter the following command in the terminal to install Workerman:

composer require workerman/workerman

After the installation is complete, we can create our first Workerman application by creating a PHP file.

require_once DIR . '/vendor/autoload.php';

// Create a Worker to listen to port 2345 and communicate using the websocket protocol
$ws_worker = new WorkermanWorker("websocket://0.0.0.0:2345");

// Start 4 processes to provide external services
$ws_worker->count = 4;

// When the client connects successfully, send a welcome message
$ws_worker->onConnect = function ($connection) {

$connection->send('Welcome to workerman!');
Copy after login

};

// When the client sends data, process it
$ws_worker->onMessage = function ($connection, $data) {

// 把收到的消息回显给客户端
$connection->send($data);
Copy after login

};

// When the client disconnects When connected, process
$ws_worker->onClose = function ($connection) {

echo "Connection closed
Copy after login
Copy after login
Copy after login

";
};

// Run Worker
WorkermanWorker: :run();

In the above code, we created a Worker to listen to port 2345 and communicate using the websocket protocol. When the client connects successfully, a welcome message will be sent; when the client sends data , the received data will be echoed to the client; when the client disconnects, a message that the connection has been closed will be output. Finally, start the Worker to run.

  1. real-time monitoring function

We have now successfully created a Workerman application, but this does not meet our real-time monitoring needs. Next, we will introduce how to use Workerman to implement real-time monitoring functions. First, we need to clarify our real-time What data does the monitoring system need to monitor? Here we take logs as an example.

2.1 Monitoring logs

Our real-time monitoring system needs to monitor the logs generated in the business system and push them to the front end in real time Display. We can monitor the log directory of the business system in the Worker's onMessage callback function, and then send the log content to the front end in real time. The code is as follows:

require_once DIR . '/vendor /autoload.php';
use WorkermanLibTimer;
use WorkermanWorker;

$ws_worker = new Worker("websocket://0.0.0.0:2345");

$ ws_worker->count = 4;

$log_dir = '/path/to/log-dir/';
$monitor_interval = 1; // Time interval for monitoring log files, unit: seconds

$ws_worker->onMessage = function ($connection, $data) use($log_dir) {

// do something
Copy after login
Copy after login

};

$ws_worker->onClose = function ( $connection) {

echo "Connection closed
Copy after login
Copy after login
Copy after login

";
};

// Monitor log file
Timer::add($monitor_interval, function () use($ws_worker, $log_dir ) {

if (!is_dir($log_dir)) {
    return;
}
$files = scandir($log_dir);
foreach ($files as $file) {
    if ($file == "." || $file == "..") {
        continue;
    }
    $filename = $log_dir . '/' . $file;
    if (is_file($filename)) {
        $fp = fopen($filename, 'r');
        $lastpos = $ws_worker->lastpos[$filename] ?? 0;
        fseek($fp, $lastpos);
        $data = fread($fp, filesize($filename) - $lastpos);
        fclose($fp);
        if (!empty($data)) {
            // 实时推送日志信息到前端
            foreach($ws_worker->connections as $con){
                if ($con->websocket) {
                    $con->send(json_encode(array(
                        'type' => 'log',
                        'data' => $data,
                        'filename' => $filename
                    )));
                }
            }
            // 更新上次读取位置
            $ws_worker->lastpos[$filename] = ftell($fp);
        }
    }
}
Copy after login

});

Workerman provides the Timer class, which can trigger a callback function regularly. We can use it to monitor the log directory regularly. When reading the log content, you need to pay attention to the last read position to avoid reading the content at the same position repeatedly. After reading the log content, push it to the front end for display in real time.

2.2 Realizing the real-time alarm function

In the real-time monitoring system, the real-time alarm function is also an indispensable part. We can send alarm information to the front end in real time when alarm events detected by monitoring occur. The following is a code example for the alert function:

require_once DIR . '/vendor/autoload.php';
use WorkermanLibTimer;
use WorkermanWorker;

$ws_worker = new Worker("websocket://0.0.0.0:2345");

$ws_worker->count = 4;

$alarm_interval = 1; // Monitor alarm events time interval, unit: seconds

$ws_worker->onMessage = function ($connection, $data) {

// do something
Copy after login
Copy after login

};

$ws_worker->onClose = function ($connection) {

echo "Connection closed
Copy after login
Copy after login
Copy after login

";
};

// Monitor alarm events
Timer::add($alarm_interval, function () use($ws_worker ) {

// 监控逻辑
$alarm_type = 'warning'; // 告警类型
$alarm_data = 'alarm data'; // 告警数据
if ($alarm_type && $alarm_data) {
    // 实时推送告警信息到前端
    foreach($ws_worker->connections as $con){
        if ($con->websocket) {
            $con->send(json_encode(array(
                'type' => 'alarm',
                'data' => $alarm_data,
                'alarm_type' => $alarm_type
            )));
        }
    }
}
Copy after login

});

Monitor alarm events regularly, and the monitoring logic is implemented according to specific business needs. When an alarm event is found to occur, the alarm information is pushed to the front end in real time.

  1. Summary

Using Workerman to implement a real-time monitoring system can help us grasp the system operating status in real time and improve the efficiency and accuracy of system operation and maintenance. This article introduces how to use Workerman to implement log monitoring and real-time alarm functions in the monitoring system, and also provides corresponding code examples. With these foundations, we can expand accordingly according to specific business needs and complete a more complete real-time monitoring system.

The above is the detailed content of How to use Workerman to implement a real-time monitoring system. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Who developed workerman Who developed workerman Apr 09, 2024 pm 07:12 PM

Workerman is co-developed by the following developers: Lv Zhiming (Gem Zhang), founder and main developer Chen Zhijun (Bruce Chen) Xie Hongliang (Qiwang) Bai Baiyu (BBYue) Li Haifeng (haiqing)

Use golang's error wrapping and unwinding mechanism for error handling Use golang's error wrapping and unwinding mechanism for error handling Apr 25, 2024 am 08:15 AM

Error handling in Go includes wrapping errors and unwrapping errors. Wrapping errors allows one error type to be wrapped with another, providing a richer context for the error. Expand errors and traverse the nested error chain to find the lowest-level error for easy debugging. By combining these two technologies, error conditions can be effectively handled, providing richer error context and better debugging capabilities.

See all articles