mammatus/http-server-websockets

🕸️🧦 HTTP服务器WebSocket

dev-master 2023-01-14 19:48 UTC

This package is auto-updated.

Last update: 2024-09-14 23:59:14 UTC


README

time docker run --rm -w `pwd` -v `pwd`:`pwd` -p 9666:9666  -it wyrihaximusnet/php:7.4-zts-alpine3.11 php ./vendor/bin/mammatus

HTTP服务器命令

Build Status Latest Stable Version Total Downloads Code Coverage License PHP 7 ready

安装

要通过Composer安装,请使用以下命令,它将自动检测最新版本并将其绑定到^

composer require reactive-apps/command-http-server

控制器

控制器分为两种类型:静态控制器和实例化控制器。

静态控制器

当您的控制器没有依赖项时,推荐使用静态控制器,例如这个ping控制器用于updown.io健康检查。 注意:/ping不是updown标准,但这是我用于应用程序健康检查的个人标准 此控制器只有一个方法和一个路由,没有依赖项

<?php declare(strict_types=1);

namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ReactiveApps\Command\HttpServer\Annotations\Method;
use ReactiveApps\Command\HttpServer\Annotations\Routes;
use RingCentral\Psr7\Response;

final class Ping
{
    /**
     * @Method("GET")
     * @Routes("/ping")
     *
     * @param  ServerRequestInterface $request
     * @return ResponseInterface
     */
    public static function ping(ServerRequestInterface $request): ResponseInterface
    {
        return new Response(
            200,
            ['Content-Type' => 'text/plain'],
            'pong'
        );
    }
}

实例化控制器

另一方面,实例化控制器将被实例化并保留以处理未来的更多请求,因此它们可以注入依赖项。以下是一个控制器示例,它将事件循环注入以等待随机秒数后返回响应。它还使用协程使代码更易于阅读

<?php declare(strict_types=1);

namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\LoopInterface;
use ReactiveApps\Command\HttpServer\Annotations\Method;
use ReactiveApps\Command\HttpServer\Annotations\Routes;
use ReactiveApps\Command\HttpServer\Annotations\Template;
use ReactiveApps\Command\HttpServer\TemplateResponse;
use WyriHaximus\Annotations\Coroutine;
use function WyriHaximus\React\timedPromise;

/**
 * @Coroutine())
 */
final class Root
{
    /** @var LoopInterface */
    private $loop;

    /** @var int */
    private $time;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
        $this->time = \time();
    }

    /**
     * @Method("GET")
     * @Routes("/")
     * @Template("root")
     *
     * @param  ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function root(ServerRequestInterface $request)
    {
        $start = \time();

        yield timedPromise($this->loop, \random_int(1, 5));

        return (new TemplateResponse(
            200,
            ['Content-Type' => 'text/plain']
        ))->withTemplateData([
            'uptime' => (\time() - $this->time),
            'took' => (\time() - $start),
        ]);
    }
}

路由

路由通过处理路由的方法上的注解来完成。每个方法可以处理多个路由,但建议只映射适合该方法的路由。

例如,以下注解将当前方法映射到/ (注意:所有路由都必须以/为前缀):@Routes("/")

多路由注解的语法略有不同,以下/old/new都将由相同的方法处理

@Routes({
    "/old",
    "/new"
})

路由的底层引擎是nikic/fast-route,它还使像这样的复杂路由成为可能

@Route("/{map:(?:wow_cata_draenor|wow_cata_land|wow_cata_underwater|wow_legion_azeroth|wow_battle_for_azeroth|wow_cata_elemental_plane|wow_cata_twisting_nether|wow_comp_wotlk)}/{zoom:1|2|3|4|5|6|7|8|9|10}/{width:[0-9]{1,5}}/{height:[0-9]{1,5}}/{center:[a-zA-Z0-9\`\-\~\_\@\%]{1,35}}{blips:/blip\_center|/[a-zA-Z0-9\`\-\~\_\@\%\[\]]{3,}.+|}.{quality:png|hq.jpg|lq.jpg}")

不同的路由组件,如mapcenter,可以通过以下方式从请求对象中获取

$request->getAttribute('center');

模板

当路由完成时,可以渲染模板。它需要一个注解,并以包含所需数据的TemplateResponse返回/解决。例如

/**
 * @Template("root")
 */
public function root(ServerRequestInterface $request)
{
    return (new TemplateResponse(
        200,
        ['Content-Type' => 'text/plain']
    ))->withTemplateData([
        'beer' => 'Allmouth', // https://untappd.com/user/WyriHaximus/checkin/745226210
    ]);
}

请求中的阻塞操作

虽然我们旨在构建一个完全非阻塞的应用程序,但我们无法逃避这样一个事实,即我们的应用程序可能总有一些部分会阻塞循环。对于这些情况,有两种方法可以处理这些情况

  • 子进程(慢,为每个工作进程生成完整的PHP进程来处理请求)
  • 线程(快,使用线程来完成工作,需要ZTS版本的PHP)

子进程

在大多数系统上(如果不是所有系统)上工作,但需要为每个工作进程使用完整的PHP进程。启动可能很慢,并且与子进程的通信通过套接字进行。将@ChildProcess注解添加到以子进程处理特定操作。

线程

仅在ZTS PHP构建上工作,但作为回报,几乎可以立即启动,通信直接在内存中进行,因此永远不会离开应用程序服务器。将@Thread注解添加到以线程处理特定操作。

注解

  • @ChildProcess - 在子进程中运行控制器操作
  • @Coroutine - 在协程中运行控制器操作
  • @Method - 允许的 HTTP 方法(GET、POST、PATCH 等)
  • @Routes - 使用给定方法的路由
  • @Template - 使用 TemplateResponse 时使用的模板
  • @Thread - 在线程中运行控制器操作(优于使用子进程)

选项

  • http-server.address - 监听的 IP + 端口,例如:0.0.0.0:8080
  • http-server.hsts - 是否设置 HSTS 头部
  • http-server.public - 要服务的公共 webroot,注意仅在此处放置所有人都可以查看的文件
  • http-server.public.preload.cache - 存储预加载 webroot 文件的自定义缓存,默认存储在内存中
  • http-server.middleware.prefix - 在 accesslog 和 webroot 服务的中间件之前添加的 react/http 中间件的数组
  • http-server.middleware.suffix - 在 accesslog 和 webroot 服务的中间件之后以及路由中间件和请求处理器之前添加的 react/http 中间件的数组
  • http-server.pool.ttl - 子进程等待其下一个任务的 TTL
  • http-server.pool.min - 子进程的最小数量
  • http-server.pool.max - 子进程的最大数量
  • http-server.rewrites - 将请求路径从一条路径内部重写为另一条路径,对访客不可见

许可证

MIT 许可证(MIT)

版权所有 (c) 2019 Cees-Jan Kiewiet

特此授予任何获得此软件和相关文档副本(“软件”)的人免费使用权,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或销售软件副本的权利,并允许软件提供者为此目的使用软件,受以下条件约束

上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。

软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定用途和非侵权性保证。在任何情况下,作者或版权所有者不对任何索赔、损害或其他责任负责,无论这些责任是基于合同、侵权或其他原因,是否由软件或软件的使用或其他方式产生。