search
HomePHP FrameworkWorkermanHow to use Workerman to implement a real-time monitoring system

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!');

};

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

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

};

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

echo "Connection closed

";
};

// 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

};

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

echo "Connection closed

";
};

// 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);
        }
    }
}

});

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

};

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

echo "Connection closed

";
};

// 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
            )));
        }
    }
}

});

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
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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.