Code Monkey home page Code Monkey logo

hyperf's Introduction

English | 中文

Hyperf Logo

Stable Version Php Version Swoole Version Hyperf License

PHPUnit for Hyperf Total Downloads Monthly Downloads

Introduction

Hyperf is an extremely performant and flexible PHP CLI framework, powered by a state-of-the-art coroutine server and a large number of battle-tested components. Aside from decisively beating PHP-FPM frameworks in benchmarks, Hyperf is unique in its focus on flexibility and composition. Hyperf ships with an AOP-enabling (aspect-oriented programming) dependency injector to ensure components and classes are pluggable and meta-programmable. All of Hyperf's core components strictly follow PSR standards and can be used in other frameworks.

Hyperf's architecture is built using a combination of Coroutines, Dependency injection, Events, Annotations, and AOP. In addition to providing MySQL, Redis and other common coroutine clients, Hyperf also provides coroutine compatible versions of WebSocket server / client, JSON RPC server / client, gRPC server / client, Zipkin/Jaeger (OpenTracing) client, Guzzle HTTP client, Elasticsearch client, Consul client, ETCD client, AMQP component, Apollo configuration center, Aliyun ACM, ETCD configuration center, Token bucket algorithm-based limiter, Universal connection pool, Circuit breaker, Swagger, Snowflake, Simply Redis MQ, RabbitMQ, NSQ, Nats, Seconds level crontab, Custom Processes, etc. Therefore, developers can entirely avoid implementing coroutine compatible versions of these libraries.

Rest assured, Hyperf is still a PHP framework. Hyperf provides all the packages you expect: Middleware, Event Manager, Coroutine-optimized Eloquent ORM (and Model Cache!), Translation, Validation, View engine (Blade/Smarty/Twig/Plates/ThinkTemplate) and more.

Origin

Although there are many new PHP frameworks, we still haven't found a framework that matches an elegant design with ultra-high performance, nor have we found a framework that paves the way for PHP microservices. With this vision in mind, we will continue to invest in the future of this framework, and you are welcome to join us in contributing to the open-source development of Hyperf.

Design Goals

Hyperspeed + Flexibility = Hyperf. The equation hidden in our name exhibits Hyperf's founding ambition.

Hyperspeed: Leveraging Swoole and Swow coroutines, Hyperf is capable of handling massive amounts of traffic. The Hyperf team made many optimizations to the framework to eliminate every bottleneck between the end-user and our blazing engine.

Flexibility: We believe our Dependency Injection component is best in class. With the help of Hyperf DI, components and classes are all pluggable and meta-programmable. Inversely, all Hyperf components are meant to be shared with the world. Our commitment to PSR standards means that you can use Hyperf components in any compatible framework.

Via these traits, Hyperf has discovered the untapped potential in many fields: implementing Web servers, gateway servers, distributed middleware software, microservices architecture, game servers, and Internet-of-Things (IoT).

Operating environment

  • Linux, OS X or Cygwin, WSL, Windows
  • PHP 8.1+
  • Swoole 5.0+ or Swow 1.4+

Production ready

Alongside our well-maintained, multilingual documentation, a large number of unit tests for each component ensure logical correctness. Before Hyperf was released to the public (2019-06-20), it had been privately used by some medium and large Internet companies for multiple services, which have been running without incident for years in harsh production environments.

Official website and Documentation

Official website https://hyperf.io
Documentation https://hyperf.wiki

Security Vulnerabilities

If you discover a security vulnerability within Hyperf, please send an e-mail to the Hyperf Team via [email protected]. All security vulnerabilities will be promptly addressed.

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Code Contributor over time

Code Contributor over time

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Support this project with your organization or company. Your logo will show up here with a link to your website. [Contribute]

Performance

Aliyun 8 cores 16G ram

command: wrk -c 1024 -t 8 http://127.0.0.1:9501/

Running 10s test @ http://127.0.0.1:9501/
  8 threads and 1024 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdevs
    Latency    10.08ms    6.82ms  56.66ms   70.19%
    Req/Sec    13.17k     5.94k   33.06k    84.12%
  1049478 requests in 10.10s, 190.16MB read
Requests/sec: 103921.49
Transfer/sec:     18.83MB

The Hyperf Ecosystem

  • 🧬 Nano is a zero-config, no skeleton, minimal Hyperf distribution that allows you to quickly build a Hyperf application with just a single PHP file.
  • ⚡️ GoTask is a library to spawns a go process as a Swoole sidecar and establishes a bi-directional IPC to offload heavy-duties to Go. Think of it as a Swoole Taskworker in Go.
  • 🚀 Jet is a unification model RPC Client, built-in JSONRPC protocol, available to running in ALL PHP environments, including PHP-FPM and Swoole/Hyperf environments.
  • 🧰 Box is committed to helping improve the programming experience of Hyperf applications, managing the PHP environment and related dependencies, providing the ability to package Hyperf applications as binary programs, and also providing reverse proxy services for managing and deploying Hyperf applications.

Stargazers over time

Stargazers over time

License

The Hyperf framework is open-source software licensed under the MIT license.

hyperf's People

Contributors

albertcht avatar assert6 avatar binaryalan avatar chunhei2008 avatar cwb2819259 avatar daydaygo avatar dickens7 avatar guandeng avatar her-cat avatar hooklife avatar huangdijia avatar huangzhhui avatar ihipop avatar limingxinleo avatar minbaby avatar nfangxu avatar nonetallt avatar osgochina avatar pandaliu-1111 avatar qifengzhang007 avatar reasno avatar starfalling avatar sy-records avatar szutoutou avatar wenbinye avatar weskiller avatar wuwu123 avatar xuanyanwow avatar yansongda avatar youmingdot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hyperf's Issues

[QUESTION] 事件重复执行

  • Hyperf Version: #.#.#
  • PHP Version: (php -v) #.#.#
  • Swoole Version: (php --ri swoole) #.#.#

Description:

/**
 * Class UserRegisteredListener
 * @Listener(priority=100)
 * @package App\Listener
 */
class UserRegisteredListener implements ListenerInterface
{
    /**
     * @var \Psr\Logger\LoggerInterface
     */
    protected $logger;

    protected static $count = 0;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('default');
    }

    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组,可以同时监听多个事件
        return [
            UserRegistered::class,
        ];
    }

    /**
     * @param UserRegistered $event
     */
    public function process(object $event)
    {
        static::$count++;
        $this->logger->debug('static count ' . static::$count);
    }
}

Result:

[2019-06-24 17:39:14] default.DEBUG: static count 1 [] []
[2019-06-24 17:39:14] default.DEBUG: static count 2 [] []

Want:

[2019-06-24 17:39:14] default.DEBUG: static count 1 [] []

[BUG] 在异步队列JOB中使用Inject注入失败

  • Hyperf Version: 1.0.1
  • PHP Version: (php -v) 7.2.19
  • Swoole Version: (php --ri swoole) 4.3.5

Description:

想在job中调用service层的方法,发现注入后的属性为null,注入失败

JOB代码

<?php

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use App\Logic\OrderHandler;
use Hyperf\Di\Annotation\Inject;

class DemoJob extends Job
{
    private $data = [];

    /**
     * @Inject
     *
     * @var OrderHandler
     */
    private $order;
    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        echo "job handle\r\n";
        var_dump($this->data);
        var_dump($this->order);
    }
}

控制台输出:

[DEBUG] Event Hyperf\AsyncQueue\Event\BeforeHandle handled by App\Listener\QueueHandleListener listener.
job handle
array(1) {
  ["a"]=>
  string(1) "b"
}
NULL

[QUESTION] 通过配置文件的方式使用Aspect无效

Before you submit this issue, you has been search all existed issues and search the documentation

  • [✅] I've been search all existed issues
  • [✅] I've been read all documentation

Describe your question

控制器

image

Service

image

Aspect类(有注解)

image

使用注解的方式,成功置空Service返回结果

Aspect类(无注解)

image

aspects配置文件

image

使用配置文件的方式,没有置空Service返回结果,在runtime/container/proxy下也没有生成代理类

[QUESTION] 工厂对象注入失败

概述:实现过程参照了官网的【工厂对象注入】章节
我的测试业务:
1.实现一个手机发短信验证码发送Service类,该类创建的时候需要初始化一些参数。
实现思路:
1.第一定义一个接口SMSInterface

<?php
/**
 * Created by PhpStorm.
 * User: shuidaosoft
 * Date: 2019-06-27
 * Time: 0:28
 */

namespace App\Service;


interface SMSInterface
{
    function sendMsg($P_telephone,$P_content);

}

2..第二创建一个短信发送类(SMS)实现接口的功能

<?php
/**
 * Created by PhpStorm.
 * User: shuidaosoft
 * Date: 2019-06-25
 * Time: 22:17
 */

namespace App\Service;

class SMS implements SMSInterface
{
    protected $params ;
    function  __construct($P_content_templete=null)
    {
        // 假设本类初始化短信验证码部分模板
        $this->params=$P_content_templete;
        var_dump("参数初始化:",$this->params);  //  使用相关参数

    }

    // 向特定手机号码发送短信验证码
    function  sendMsg($to_telephone,$send_content)
    {

        var_dump($to_telephone,$send_content);  //  向特定手机号码发送短消息

    }
}

3.第三定义一个工厂类(服务提供者),创建短信发送类(SMS)对象,初始化参数

<?php
/**
 * Created by PhpStorm.
 * User: shuidaosoft
 * Date: 2019-06-25
 * Time: 22:30
 */

namespace App\ProviderService;

use Hyperf\Contract\ConfigInterface;
use Psr\Container\ContainerInterface;
use App\Service\SMS;

class SmsProvider
{
    // 实现一个 __invoke() 方法来完成对象的生产,方法参数会自动注入一个当前的容器实例
    public function __invoke(ContainerInterface $container)
    {
        //$config = $container->get(ConfigInterface::class);
        // 我们假设对应的配置的 key 为 cache.enable
        //$configParams = $config->get('config.app_name', '无appname');
        // make(string $name, array $parameters = []) 方法等同于 new ,使用 make() 方法是为了允许 AOP 的介入,而直接 new 会导致 AOP 无法正常介入流程
        return make(SMS::class,   ['key1'=>'配置参数']    );
        //return make(SMS::class, compact('configParams'));
    }
}

4.定义依赖注入关系config/dependencies.php

<?php

return [
    'dependencies' => [
         \App\Service\SMSInterface::class=>  \App\ProviderService\SmsProvider::class
    ],
];

5.注入短信发送类,调用功能:

<?php

declare(strict_types=1);

namespace App\Controller\Api\V1;

use App\Controller\Controller;
use \App\Service\SMSInterface;

class TestController extends Controller
{

    public function index(SMSInterface $sms)
    {

        $sms->sendMsg('16601770915','你好,测试短消息');
     //return $temp->sendMsg('16601770915','你好,测试短消息');
    }

}
  1. 运行结果:
string(18) "参数初始化:"
NULL   //   实际调用的时候,SM类的默认参数初始化失败,没有传递进去
string(11) "16601770915"
string(24) "你好,测试短消息"

[Command]创建中间件,位置存在小bug

php

PHP 7.3.5 (cli) (built: Jun 5 2019 11:24:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.5, Copyright (c) 1998-2018 Zend Technologies

swoole

Swoole => enabled
Author => Swoole Team [email protected]
Version => 4.3.2

Error detail:

//使用Command命令创建中间件,文件夹大小写异常 相关文件的文件自动创建在App/.....开头的文件夹,并不是app/....
1.php  ./bin/hyperf.php    gen:middleware   Auth/verrifyMiddleware

centos
NAME="CentOS Linux"
VERSION="7 (Core) X64"

[QUESTION] Http Request请求请默认允许跨域

【文件】 Hyperf\HttpServer\Server

【行数】:96
【为了默认允许跨域,需要增加以下代码】:

        try {
//  允许跨域开始
            $response->header('Access-Control-Allow-Origin', '*');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, PATCH, OPTIONS');
            $response->header('Access-Control-Allow-Headers', 'Authorization, User-Agent, Keep-Alive, Content-Type, X-Requested-With');
            if ($response->server['request_method'] == 'OPTIONS') {
                $response->status(http_response_code());
                $response->end();
                return;
            }
//  允许跨域截止

            [$psr7Request, $psr7Response] = $this->initRequestAndResponse($request, $response);

            $middlewares = array_merge($this->middlewares, MiddlewareManager::get($this->serverName, $psr7Request->getUri()->getPath(), $psr7Request->getMethod()));

            $psr7Response = $this->dispatcher->dispatch($psr7Request, $middlewares, $this->coreMiddleware);
        } 

[QUESTION] make 函数初始化对象,传参无效

将一个类初始化在容器的时候,
`
// make(string $name, array $parameters = []) 方法等同于 new ,使用 make() 方法是为了允许 AOP 的介入,而直接 new 会导致 AOP 无法正常介入流程
make(UserService::class, compact('enableCache'));

`
被初始化的对象传输传递不进去。具体的service对象一直收不到参数。

[FEATURE] 支持服务平滑重启吗?

支持服务平滑重启吗?比如消费者正在消费某条消息(可能处理到一半,已经进行了一些写库或者远程服务调用的操作),这时候服务停止的话,消费者进程会立即结束还是消费完再结束?

[QUESTION] guzzlephp使用curl handler死循环问题

Before you submit this issue, you has been search all existed issues and search the documentation

  • [✅] I've been search all existed issues
  • [✅] I've been read all documentation

Describe your question

在使用http 客户端的时候想看一下支持协程和不支持协程的区别,按照文档使用guzzle 协程客户端没问题可以正常运行,但使用curl hanlder的时候就会被夯住,strace发现死循环了。这个应该跟HF没关系,裸写swoole可以复现,代码如下:

<?php
require './vendor/autoload.php'; 
$http = new Swoole\Http\Server("127.0.0.1", 9505);
$http->set([
    'enable_coroutine' => true,
    'reload_async' => true,
    'worker_num' => 1,
    'open_tcp_nodelay' => true,
    'max_coroutine' => 100000,
    'open_http2_protocol' => true,
    'max_request' => 1,
]);
$http->on('request', function ($request, $response) {
    $handler = new \GuzzleHttp\Handler\CurlHandler();
    $stack = \GuzzleHttp\HandlerStack::create($handler);
    $client = new Client(['handler' => $stack]);
    $result = $client->request('GET', 'http://www.baidu.com');
    $response->end($result->getBody()->getContents());
});
$http->start();

[启动服务报错] 提示swoole.user_shortname必须为Off,但是swoole配置已经是Off

php

PHP 7.3.5 (cli) (built: Jun 5 2019 11:24:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.5, Copyright (c) 1998-2018 Zend Technologies

swoole

Swoole => enabled
Author => Swoole Team [email protected]
Version => 4.3.2
Built => Jun 20 2019 23:32:57
coroutine => enabled
epoll => enabled
eventfd => enabled
signalfd => enabled
cpu_affinity => enabled
spinlock => enabled
rwlock => enabled
http2 => enabled
pcre => enabled
zlib => enabled
mutex_timedlock => enabled
pthread_barrier => enabled
futex => enabled
async_redis => enabled

Directive => Local Value => Master Value
swoole.enable_coroutine => On => On
swoole.display_errors => On => On
swoole.use_shortname => Off => Off
swoole.unixsock_buffer_size => 8388608 => 8388608

Error detail:
Scanning ...
Scan completed.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\JsonRpc\Listener\RegisterProtocolListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
ERROR Swoole short name have to disable before start server, please set swoole.use_shortname = 'Off' into your php.ini.

centos
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

启动服务时报错

php version 7.3.6
swoole 4.3.5
项目里输入php bin/hyperf.php start时报错如下:
Scanning ...
Scan completed.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
ERROR Swoole short name have to disable before start server, please set swoole.use_shortname = 'Off' into your php.ini.

php --ri swoole如下:

swoole

Swoole => enabled
Author => Swoole Team [email protected]
Version => 4.3.5
Built => Jun 21 2019 11:52:03
coroutine => enabled
epoll => enabled
eventfd => enabled
signalfd => enabled
cpu_affinity => enabled
spinlock => enabled
rwlock => enabled
http2 => enabled
pcre => enabled
zlib => enabled
mutex_timedlock => enabled
pthread_barrier => enabled
futex => enabled
async_redis => enabled

Directive => Local Value => Master Value
swoole.enable_coroutine => On => On
swoole.display_errors => On => On
swoole.use_shortname => On => On
swoole.unixsock_buffer_size => 8388608 => 8388608

grpc client how to add header like content-type

Before you submit this issue, you has been search all existed issues and search the documentation

  • [] I've been search all existed issues
  • [] I've been read all documentation

Describe your question

php grpc client -> springboot grpc server
image
但是我没有发现怎么自定义header头,就像这样
image

[BUG] 当有多个异常处理器时,对象注入失败

  • Hyperf Version: 1.0.0
  • PHP Version: (php -v) 7.2.18
  • Swoole Version: (php --ri swoole) 4.3.5

Description:

当有多个异常处理器时,异常处理器中handle方法注入失败。

Steps To Reproduce:

新增异常处理器,app/Exception/Handler/OrderExceptionHandler.php

<?php
namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use App\Exception\OrderException;
use App\Helper\Log;

class OrderExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
       
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}

注册异常处理器

return [
    'handler' => [
        'http' => [
            App\Exception\Handler\OrderExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,
        ],
    ],
];

控制器诱发异常

$request->header();

控制台显示注入异常
image

[BUG] Guzzle HTTP 协程客户端在处理https请求时异常。

  • Hyperf Version: 1.0.1
  • PHP Version: (php -v) 7.2.18
  • Swoole Version: (php --ri swoole) 4.3.5

Description:

使用原生 GuzzleHttp 客户端与框架提供的 Guzzle HTTP 协程客户端,在处理相同请求时,一个能正常拿到结果,一个异常。

Steps To Reproduce:

原生的可以正常返回错误

        $client = new \GuzzleHttp\Client();
        $response = $client->request('POST', 'https://218.18.231.137:8065/polypay/v1.0/mchorders/onlinepay',[
            \GuzzleHttp\RequestOptions::JSON => [
                'a' => 'a',
                'b' => 'b',
            ],
            \GuzzleHttp\RequestOptions::VERIFY => false,
            \GuzzleHttp\RequestOptions::HEADERS => [
                'appid' => '8ab74856-8772-45c9-96db-54cb30ab9f74',
                'timestamp' => '1561536304',
                'apisign' => '7f04cb6bcd787daba31caf7ef569e4f4',
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ]
        ]);

        return $response->getBody()->getContents();

协程客户端就收到一条错误日志。

"message":"Connection failed, errCode=0",
        $container = ApplicationContext::getContainer();
        $factory = $container->get(\Hyperf\Guzzle\ClientFactory::class);
        $client = $factory->create();

        $response = $client->request('POST', 'https://218.18.231.137:8065/polypay/v1.0/mchorders/onlinepay',[
            \GuzzleHttp\RequestOptions::JSON => [
                'a' => 'a',
                'b' => 'b',
            ],
            \GuzzleHttp\RequestOptions::VERIFY => false,
            \GuzzleHttp\RequestOptions::HEADERS => [
                'appid' => '8ab74856-8772-45c9-96db-54cb30ab9f74',
                'timestamp' => '1561536304',
                'apisign' => '7f04cb6bcd787daba31caf7ef569e4f4',
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ]
        ]);

        return $response->getBody()->getContents();

由于这个接口的访问需要服务端添加IP白名单,所以你们也没法测试。

[QUESTION] Redis 持久化对象是如何解决协程间混淆问题的?

  1. redis配置:
return [
    'default' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'auth' => env('REDIS_AUTH', ''),
        'port' => (int) env('REDIS_PORT', 6379),
        'db' => (int) env('REDIS_DB', 0),
        'pool' => [
            'min_connections' => 1,
            'max_connections' => 10,   
            'connect_timeout' => 10.0,
            'wait_timeout' => 3.0,
            'heartbeat' => -1,
            'max_idle_time' => (float) env('REDIS_MAX_IDLE_TIME', 60),
        ],
    ],
];

请问一下max_connections 这个值意义是什么?假设同时在线客户端有10万,这个值应该设置多少?

2.我使用redis的部分代码

namespace App\Service;

use Psr\Container\ContainerInterface;
use App\Model\MembersMac;
class ConnectionPoolService
{
    protected $container ;
    protected $client_redis ;
    protected $MembersMac ;
    const  HASH_KEY ='box3';

    function  __construct(ContainerInterface $container,MembersMac $membersMac)
    {
        $this->client_redis=$this->container->get(\Redis::class) ;   
        $this->container=$container;
        $this->MembersMac=$membersMac;
    }

   function   fun_deal_business(){
    //   TODU........
    $this->client_redis->......
  }

以上代码是我实现业务的部分代码,请问一下:
swoole启动的时候, $this->client_redis 值只会初始化一次(=单例对象),后续的业务请求, $this->client_redis都只是第一次初始化好的,那么后续的请求,获取的返回值在高并发的时候本质上都是通过单例对象获取,返回的,因此会不会出现业务请求代码拿错值的情况?
此外,redis配置文件的连接池和我从容器解析的redis对象什么关系?
能解答一下吗?
因为我之前的项目基于swoole没有处理好单例对象,结果出现了返回值串号的情况。

[Router] router::add 和Router::groupAddd定义的路由无法访问

php

PHP 7.3.5 (cli) (built: Jun 5 2019 11:24:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.5, Copyright (c) 1998-2018 Zend Technologies

swoole

Swoole => enabled
Author => Swoole Team [email protected]
Version => 4.3.2
Built => Jun 20 2019 23:32:57
coroutine => enabled
epoll => enabled
eventfd => enabled
signalfd => enabled
cpu_affinity => enabled
spinlock => enabled
rwlock => enabled
http2 => enabled
pcre => enabled
zlib => enabled
mutex_timedlock => enabled
pthread_barrier => enabled
futex => enabled
async_redis => enabled

Directive => Local Value => Master Value
swoole.enable_coroutine => On => On
swoole.display_errors => On => On
swoole.use_shortname => Off => Off
swoole.unixsock_buffer_size => 8388608 => 8388608

Error detail:

1.路由定义无法正藏访问
//  ok ,正常访问相关控制器、函数
Router::get('/hello', 'App\Controller\IndexController@index');

//1. 访问相关控制器函数出错,后台无错误日志,浏览器页面405
  Router::addRoute(
    ['get'],   //  大小写都已经测试,效果一致
    '/world',
    'App\Controller\IndexController@index'
  );


// 2.以Users 表模型为例,定义一个增删改查路由,同样无法访问

  Router::addGroup('user',function (){
    //1. 查询
    Router::addRoute(
        ['GET'],
        'index',
        'App\Controller\Api\V1\UserController@index'
    );

    //2.修改
    Router::addRoute(
        ['POST'],
        'update/{id}',
        'App\Controller\Api\V1\UserController@update'
    );
    //2.删除
    Router::addRoute(
        ['POST'],
        'delete',
        'App\Controller\Api\V1\UserController@delete'
    );

});

centos
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

[BUG] 创建迁移文件在没有migrations目录情况下会失败

  • Hyperf Version: v1.0.3
  • PHP Version: (php -v) 7.2
  • Swoole Version: (php --ri swoole) 4.3.5

Description:

创建迁移文件时 报错提示:
file_put_contents(/path/hyperf/migrations/2019_07_04_165205_create_shop_orders_table.php): failed to open stream: No such file or directory in /path/hyperf/vendor/hyperf/utils/src/Filesystem/Filesystem.php on line 120

Steps To Reproduce:

php bin/hyperf.php gen:migration create_shop_orders_table --create=shop_orders

[BUG] Redis数据库选择索引的bug

1.redis配置:

    'default' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'auth' => env('REDIS_AUTH', ''),
        'port' => (int) env('REDIS_PORT', 6379),
        'db' => (int) env('REDIS_DB', 0),   //  这里选择的数据库索引我配置的是1 
        'pool' => [
            'min_connections' => 1,
            'max_connections' => 10,
            'connect_timeout' => 10.0,
            'wait_timeout' => 3.0,
            'heartbeat' => -1,
            'max_idle_time' => (float) env('REDIS_MAX_IDLE_TIME', 60),
        ],
    ],

2.由于在程序中,我们的数据分布在好几个不同的db索引,这个时候需要跨redis数据库的索引查询,

...
 $this->client_redis=$this->container->get(\Redis::class) ;
.....
 $this->client_redis->select(7);  //  
 $this->client_redis->get('key')   //  这个时候查询的数据并不是索引为7的值,仍然是索引为初始化配置时设置的索引 1  所在的数据库值。

[QUESTION] 希望获取到向客户端主动发送消息的demo

Before you submit this issue, you has been search all existed issues and search the documentation

  • I've been search all existed issues
  • I've been read all documentation

Describe your question

我想做到 服务端主动向客户端推送消息,我觉得我需要一个task来推送消息,思路应该是正确的。但是在获取对应的终端信息时犯难了,我不知道终端连接信息是怎么保存到数据库(或者redis之类)中,然后能够直接走现有的连接通道发送消息,还请给予一个指导。

[QUESTION] max_request设置成1的问题

Before you submit this issue, you has been search all existed issues and search the documentation

  • [✅] I've been search all existed issues
  • [✅] I've been read all documentation

Describe your question

由于HF不支持reload,而每次修改代码后重启又相对麻烦,所以想在开发环境通过设置max_request=1来刷新业务代码,但设置成1后访问就会一直夯住,请教一下是为什么呢?

[FEATURE] 是否可以考虑下路由中可以想 laravel 那样动态添加命名空间

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

[FEATURE] Redis超时设置

Is your feature request related to a problem? Please describe.

Describe the solution you'd like
Redis组件支持连接超时,超时重试以及读写超。phpredis文档

Describe alternatives you've considered

Additional context

[BUG] Router::addGroup继承的中间件无效

Router::addGroup('/api', function () { Router::get('/v1/test', [\App\Controller\IndexController::class, 'testMiddleware']); }, ['middleware' => [\App\Middleware\Auth\BarMiddleware::class]] );

Router::addGroup添加的中间件不执行

Uncaught Swoole\Error on execute php bin/hyperf.php start

php

PHP 7.3.6 (cli) (built: Jun 17 2019 08:40:34) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.6, Copyright (c) 1999-2018, by Zend Technologies

swoole:


swoole

Swoole => enabled
Author => Swoole Team <[email protected]>
Version => 4.4.0-beta
Built => Jun 20 2019 14:36:39
coroutine => enabled
kqueue => enabled
rwlock => enabled
http2 => enabled
pcre => enabled
zlib => enabled
brotli => enabled
async_redis => enabled

Directive => Local Value => Master Value
swoole.enable_coroutine => On => On
swoole.enable_library => On => On
swoole.enable_preemptive_scheduler => Off => Off
swoole.display_errors => On => On
swoole.use_shortname => On => On
swoole.unixsock_buffer_size => 262144 => 262144

Error detail:

Scanning ...
Scan completed.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
PHP Fatal error:  Uncaught Swoole\Error: API must be called in the coroutine in /www/hyperf/vendor/symfony/console/Terminal.php:127
Stack trace:
#0 /www/hyperf/vendor/symfony/console/Terminal.php(127): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#1 /www/hyperf/vendor/symfony/console/Terminal.php(70): Symfony\Component\Console\Terminal::getSttyColumns()
#2 /www/hyperf/vendor/symfony/console/Terminal.php(51): Symfony\Component\Console\Terminal::initDimensions()
#3 /www/hyperf/vendor/symfony/console/Application.php(116): Symfony\Component\Console\Terminal->getHeight()
#4 /www/hyperf/bin/hyperf.php(22): Symfony\Component\Console\Application->run()
#5 /www/hyperf/bin/hyperf.php(23): {closure}()
#6 {main}
  thrown in /www/hyperf/vendor/symfony/console/Terminal.php on line 127

Fatal error: Uncaught Swoole\Error: API must be called in the coroutine in /www/hyperf/vendor/symfony/console/Terminal.php:127
Stack trace:
#0 /www/hyperf/vendor/symfony/console/Terminal.php(127): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#1 /www/hyperf/vendor/symfony/console/Terminal.php(70): Symfony\Component\Console\Terminal::getSttyColumns()
#2 /www/hyperf/vendor/symfony/console/Terminal.php(51): Symfony\Component\Console\Terminal::initDimensions()
#3 /www/hyperf/vendor/symfony/console/Application.php(116): Symfony\Component\Console\Terminal->getHeight()
#4 /www/hyperf/bin/hyperf.php(22): Symfony\Component\Console\Application->run()
#5 /www/hyperf/bin/hyperf.php(23): {closure}()
#6 {main}
  thrown in /www/hyperf/vendor/symfony/console/Terminal.php on line 127

[QUESTION] 请问一下db链接 没有port 设置的么?还是直接在host:port 这样?

如题:谢谢
下面是官网文档配置项

[ 'driver' => env('DB_DRIVER', 'mysql'), 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'hyperf'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD', ''), 'charset' => env('DB_CHARSET', 'utf8'), 'collation' => env('DB_COLLATION', 'utf8_unicode_ci'), 'prefix' => env('DB_PREFIX', ''), 'pool' => [ 'min_connections' => 1, 'max_connections' => 10, 'connect_timeout' => 10.0, 'wait_timeout' => 3.0, 'heartbeat' => -1, 'max_idle_time' => (float)env('DB_MAX_IDLE_TIME', 60), ] ], ];

[FEATURE] 开发环境加快重启速度

mac + docker 模式下重启应用会消耗大概5秒左右时间,大部分时间都消耗在Scanning上,建议把annotations.cache的开关暴露出来由开发者自主选择是否使用缓存

[question] `destroy` method of Model does not work expected

【文件】

/hyperf-skeleton-master/vendor/hyperf/database/src/Model/Model.php

【行数】 565

【错误位置】

    public static function destroy($ids){
	........
	}
	

【问题分析】

结合官方文档:
https://doc.hyperf.io/#/zh/db/model?id=%e5%88%a0%e9%99%a4%e6%a8%a1%e5%9e%8b

通过主键删除模型章节,经过调试代码确认,
需要删除上一段落中的static修饰符,$this->destroy () 直接调用。
如果不删除static,就得修改官网文档:

User::query()->destroy([1,2,3]);   ====>  User::destroy([1,2,3]);  

否则框架运行报错:

[ERROR] Call to undefined method Hyperf\Database\Query\Builder::destroy()[52] in /home/wwwroot/www.hyperf.com/backend/vendor/hyperf/utils/src/Traits/ForwardsCalls.php
[ERROR] #0 /home/wwwroot/www.hyperf.com/backend/vendor/hyperf/database/src/Query/Builder.php(266): Hyperf\Database\Query\Builder::throwBadMethodCallException('destroy')
#1 /home/wwwroot/www.hyperf.com/backend/vendor/hyperf/utils/src/Functions.php(275): Hyperf\Database\Query\Builder->__call('destroy', Array)
#2 /home/wwwroot/www.hyperf.com/backend/vendor/hyperf/database/src/Model/Builder.php(146): call(Array, Array)
#3 /home/wwwroot/www.hyperf.com/backend/app/Model/Model.php(45): Hyperf\Database\Model\Builder->__call('destroy', Array)
#4 /home/wwwroot/www.hyperf.com/backend/app/Model/User.php(50): App\Model\Model->deleteData('1029,1030')
#5 /home/wwwroot/www.hyperf.com/backend/app/Controller/Api/V1/UserController.php(70): App\Model\User->delete_data('1029,1030')

[BUG] 模型支持array类型字段,但是模型缓存不支持。

  • Hyperf Version: 1.0.1
  • PHP Version: (php -v) 7.2.19
  • Swoole Version: (php --ri swoole) 4.3.5

Description:

模型支持array类型字段,但是模型缓存不支持。
数组类型字段能成功写入数据库,保存为json格式,但是用 findFromCache 获取之后,在redis缓存里面字段对应的值是"Array"字符串,应该是个json串才对。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.