Swoole based Simple HTTP Server Implementation using OSS PHP SDK

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: Currently, program developers are leveraging Swoole to implement network server programs in place of C++, Java and other complex programming languages.

0213_Android_DevOps_from_a_single_push_command_to_production

Introduction

Swoole, in the recent times, has taken over as the new "best language" in the coder's world.

As described officially, it is a high-performance network communication engine for PHP asynchronous and parallel requests. Its compilation purely utilizes the C language that provides PHP asynchronous multi-threaded server, asynchronous TCP/UDP network client, and asynchronous MySQL. Additionally, it uses asynchronous Redis, database connection pool, AsyncTask, message queue, millisecond timer, asynchronous file reads and writes, and asynchronous DNS query features. It is nested with HTTP/WebSocket server/ client and HTTP 2.0 server.

Swoole 2.0 supports a coroutine, such as Go language, to enable the use of fully synchronized code to implement an asynchronous program. The PHP code does not require additional keywords. Furthermore, the bottom layer automatically schedules the coroutine to implement asynchronous processing.

Advantages of Swoole

Let us examine its advantages.

●Purely C-compiled, with extremely powerful performance;
●Simple and easy to use, development-efficient;
●Event-driven, non-blocking asynchronous processing;
●Supporting millions of concurrent TCP connections;
●TCP/UDP/UnixSock;
●Server/client;
●Supporting asynchronous/synchronous/coroutine;
●Supporting multiprocessing/multi-threading;
●CPU affinity/daemon process;
●Supporting IPv4/IPv6 networks.

Application Scenario

To understand Swoole more comprehensively, let us look at a use-case for Swoole.

Currently, program developers are leveraging Swoole to implement network server programs in place of C++, Java and other complex programming languages. It has been in use by several mobile internet, Internet of Things, online games and mobile gaming organizations. The combination of PHP and Swoole can considerably improve development efficiency.

An officially provided PHP network framework extended and developed based on Swoole supports HTTP, FastCGI, WebSocket, FTP, SMTP, RPC and other network protocols.

Swoole users are everywhere, spread out across the United States, Britain, France, India and other countries. Several well-known internet companies in China such as Tencent, Baidu, Alibaba and YY Language also use this product.

Further, let us now delve into functioning with Swoole using OSS PHP SDK.

1. Install Swoole

As the first step, you need to install Swoole on your system. If you have PHP7 and PECL installed, you can use the following command directly.
pecl install swoole

Then locate the specific Loaded Configuration File using php -info | grep php.ini.
It may be different for different environments, in ours it is /etc/php/7.0/cli/php.ini.
Then, you need to run
vim /etc/php/7.0/cli/php.ini

Next, add
extension = "swoole.so"

Or you may compile and install Swoole in your system. However, you need to do this until you can see the text shown in the following screenshot.

1

2. Use OSS PHP SDK

For using Swoole in OSS PHP SDK, you need to ensure that the PHP SDK setup is successful and ready. The steps are as follows:

●git clone https://github.com/aliyun/aliyun-oss-php-sdk.git # Download the code from the OSS PHP SDK code address.
●Run cd aliyun-oss-php-sdk/.
●Configure samples/Config.php #.
●php sample/Swoole.php # Run a sample program
●Run curl 127.0.0.1:9503.
●"Hello Swoole" should display on your screen.

2

Once it displays, Swoole and OSS PHP SDK are ready for use, together.

3. Set Nginx for Reverse Proxy

After carrying out the steps mentioned above, you can access OSS through Swoole. However, the more common practice, on the server side, is to use nginx as a front-end proxy. Then access the initiated Swoole server through the nginx reverse proxy server.

Specific steps to carry it out are as below (You may skip these if you have already installed nginx.).

●Download the latest version from wget http://nginx.org/download/nginx-1.11.3.tar.gz
●Next, unzip the package using tar -zxvf nginx-1.11.3.tar.gz \
●Then enter the command cd nginx-1.11.3
●Now, configure the software through ./configure --prefix=/usr/local/nginx #
●Please make a note that the following error may occur at this step "pcre.h No such file or directory".
●You can find an=bout more about this error here.
●Further, you need to install libpcre3-dev with the command: sudo apt-get install libpcre3-dev
●sudo make install
●sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
●Note: The "-c" specifies the path to the configuration file. If you do not add it, nginx will automatically load the configuration file at the default path. You can view the help command via "-h".
●ps -ef | grep nginx
●You can view the nginx progress here:

3

If you can see the above screenshot on your screen, it indicates that nginx is working normally.

Next, we will use nginx reverse proxy 127.0.0.1:9503 and modify /usr/local/nginx/conf/nginx.conf.

You can execute it as follows:

http {
    include       mime.types;
    default_type  application/octet-stream;
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
        upstream swoole{
                server 127.0.0.1:9503;
                keepalive 4;
        }
    server {
        listen       80;
        server_name  www.swoole.com;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http://swoole;
            proxy_set_header Connection "";
            proxy_http_version 1.1;
            root   html;
            index  index.html index.htm;
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

●Now, you need to reload nginx to bring the configuration into effect with the command: sudo /usr/local/nginx/sbin/nginx -s reload.

●Next, add 127.0.0.1 www.swoole.com in vim /etc/hosts.

●To verify the result, you can use curl www.swoole.com or the browser to open the domain name and check whether "Hello Swoole" is displaying on your screen.

4. Experiences using Swoole

If "Hello Swoole" is the only result after following the steps until now, then you are missing something.

Let us move forward and see what could be missing? There is a sample.jpg file in the ./aliyun-oss-php-sdk directory for your reference and use. The sample code for uploading the file is as follows:

<?php
require_once __DIR__ . '/Common.php';

use OSS\OssClient;
use OSS\Core\OssException;

$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple use***************************************************************
$options = array(
    OssClient::OSS_FILE_DOWNLOAD => "example_download.jpg",
);

$ossClient->uploadFile($bucket, "example.jpg", "example.jpg");
$ossClient->getObject($bucket, "example.jpg", $options);

You should check the result after executing the command.

4

The simplest file upload/download methods in OSS is as below.

Call the OSS PHP SDK in the Swoole server following the steps above. Then use the server as the nginx proxy. Next, the simplest OSS upload/download code will be changed as below. :

<?php
require_once __DIR__ . '/Common.php';

use OSS\OssClient;
use OSS\Core\OssException;

$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple use***************************************************************

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => "example_download.jpg",
);

$serv = new swoole_http_server("127.0.0.1", 9503);

$serv->set(array(
        'worker_num' => 16,
        'daemonize' => true,
        'max_request' => 10000,
        'dispatch_mode' => 2,
        'debug_mode'=> 1,
        'log_file' => '/tmp/swoole_http_server.log',
));

$serv->on('Request', function($request, $response) use($ossClient, $bucket, $options){

        $ossClient->uploadFile($bucket, "example.jpg", "example.jpg");
        $ossClient->getObject($bucket, "example.jpg", $options);

        $response->end("Hello Swoole\n");
});

$serv->start();

●php sample/Swoole.php
●Now, you need to run the command: curl www.swoole.com.

Do you receive no response for a long time and nginx reports an error?
Check the nginx access log and you will find the 504 error. Open the swoole_http_server.log that we set in Swoole and you will find the following on your screen:

5

The two problems that you may face are:

●Problem 1: The error indicates that OSS PHP SDK failed to find this example.jpg file. However, example.jpg is a local file. Why can't OSS PHP SDK find it?
●Problem 2: Even if this error is true, why did it cause nginx to report the 504 error?

Now, you may be wondering, how can you solve these two problems?

Problem 1 could arise from a bug of Swoole. An actual test showed that Swoole calculates the relative path from the root directory "/", rather than the current directory. You can then write a resolution path for the file.

For Problem 2, Swoole users must encapsulate the error thrown by the called interface. That means that the error thrown by OSS PHP SDK in the case of this article is to allow nginx to identify it correctly.

Conclusion

The event-based network layer in Swoole takes advantage of the underlying epoll/kqueue implementation to cater to several thousand connections. After a request, the allocated memory does not free itself as it does in legacy apache/php-fpm, improving its performance significantly. You can create enhanced web applications with more control, real-time chatting servers, and much more with Swoole.

相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
1月前
|
存储 JavaScript 前端开发
oss使用SDK上传文件
oss使用SDK上传文件
105 2
|
8月前
|
开发工具 对象存储 Python
使用Python的SDK从OSS中下载指定日期的所有文件
使用Python的SDK从OSS中下载指定日期的所有文件
206 1
|
3天前
|
存储 移动开发 前端开发
对象存储oss使用问题之OSS SDK .net 使用下载例程报错如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
19 0
|
3天前
|
安全 网络安全 开发工具
对象存储oss使用问题之flutter使用http库进行post请求文件上传返回400如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
16 1
|
1月前
|
Rust API 开发工具
Rust初学者,边学边写的OSS的sdk,欢迎批评指正 :)
`Rust`语言编写的阿里云OSS的SDK,依据官方文档并参考了其他语言的实现。
212 5
Rust初学者,边学边写的OSS的sdk,欢迎批评指正 :)
|
2月前
|
对象存储
阿里云oss-cloud-sdk-springboot3兼容问题
阿里云oss-cloud-sdk-springboot3兼容问题
70 0
|
3月前
|
JavaScript Java Serverless
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
159 0
|
4月前
|
存储 DataWorks 开发工具
在DataWorks中,可以使用Python SDK操作阿里云OSS存储服
在DataWorks中,可以使用Python SDK操作阿里云OSS存储服
134 1
|
9月前
|
存储 弹性计算 安全
HTTP、CDN 和 OSS 为什么过时了?深入聊聊 Web3 世界中的协议和硬盘:IPFS
HTTP、CDN 和 OSS 为什么过时了?深入聊聊 Web3 世界中的协议和硬盘:IPFS
217 0
|
10月前
|
SQL 存储 监控
通过sdk查看oss投递(新版)延迟情况最佳实践
在投递任务中,日志服务会将运行日志写入到给定的logstore中,因而可以使用SDK来查看投递任务的当前状态,并进行批量查询,以了解多个Project和投递任务的状态。下面以查看oss投递的延迟为例,介绍客户提供操作步骤和常见的使用场景,以帮助客户更加方便地监控和管理投递任务。
通过sdk查看oss投递(新版)延迟情况最佳实践