simple-handle toolkit

v2.1.8.1 2024-03-06 13:55 UTC

README

介绍

  • redis和mysql的pdo链接基于swoole协程下使用
  • UtilXls excel表格操作基于Xlswriter 扩展
  • 其他插件可在任何环境中使用

软件架构

swoole Xlswriter pdo

安装教程

composer require simple-handle/util

使用说明

RabbitMQ

参考文档 php-amqplib

继承 simpleHandle\Component\UtilMQ\RabbitMQ 类

use simpleHandle\Component\UtilMQ\RabbitMQ;
class MQ extends RabbitMQ
{
    /**
    * @throws Exception
    */
    public function __construct() {
        $mqConfig = [
            "host"         => "127.0.0.1",
            "port"         => 5672,
            "username"     => "guest",
            "password"     => "guest",
            "vhost"        => "/",
            "exchangeName" => "exchangeName",
            "queuePrefix"  => "queuePrefix"
	    ];
        parent::__construct( $mqConfig );
    }
}

$MQ = new MQ();
属性方法类型描述
MQConnAMQPStreamConnectionMQ链接
MQChanAMQPChannelMQ通道
messageIdstringMQ 发送消息的消息ID
exchangeNamestring交换机名
queuePrefixstring队列名前缀
exchangeDeclarefunction创建Exchange交换机
queueDeclarefunction创建Queue队列
queueBindfunction队列绑定
publishfunction发送队列消息(生产者)
consumerfunction监听队列消息(推模式)(消费者)
sendfunction发送队列消息封装(生产者)
listenfunction监听队列消息封装(推模式)(消费者)
closefunction关闭MQConn 关闭MQChan
配置
配置项必填配置值类型
host127.0.0.1string
port5672int
usernamegueststring
passwordgueststring
vhost/string
exchangeNameexchangeNamestring
queuePrefixqueueNamestring
MQConn

获取MQ链接

$MQ->MQConn
MQChan

获取MQ通道Channel

$MQ->MQChan
messageId

获取消息ID

exchangeDeclare

创建Exchange交换机

// @throws UtilException
$MQ->exchangeDeclare( string $exchangeName, string $type, bool $durable, bool $autoDelete, array $arguments = array() )
参数
参数类型描述
$exchangeNamestring交换机名称
$typestringdirect | fanout | headers | topic
$durablebool是否持久化
$autoDeletebool是否自动删除
$argumentsarray参数
queueDeclare

创建Queue队列

// @throws UtilException
$MQ->queueDeclare( string $queueName, bool $durable, bool $autoDelete, $arguments = array() )
参数
参数类型描述
$queueNamestring队列名称
$durablebool是否持久化
$autoDeletebool是否自动删除
$argumentsarray参数
queueBind

绑定队列

// @throws UtilException
$MQ->queueBind( string $queueName, string $exchangeName, string $routingKey, array $arguments = array() )
参数
参数类型描述
$queueNamestring队列名称
$exchangeNamestring交换机名称
$routingKeystring路由键
$argumentsarray参数
publish

发送MQ消息

// @throws UtilException
$MQ->publish( AMQPMessage $msg, string $exchangeName, string $routingKey )
参数
参数类型描述
$msgAMQPMessageMQ消息
$exchangeNamestring交换机名称
$routingKeystring路由键
consumer
// @throws UtilException
$callback = function(AMQPMessage $msg){
  // 处理消息逻辑......
  // ack
  $msg->getChannel()->basic_ack( $msg->getDeliveryTag() );
}
$MQ->consumer(
		string   $queueName,
		string   $tag,
		bool     $noAck,
		callable $callback,
		array    $arguments = array(),
		int      $prefetchSize = null,
		int      $prefetchCount = 1,
		bool     $nonBlocking = false,
		int      $timeOut = 0
	)
参数
参数类型默认值描述
$queueNamestring队列名
$tagstring消费者标签(区分不同消费者)
$noAckbool是否自动进行ACK
$callbackcallable消息回调处理
$argumentsarrayarray()参数
$prefetchSizeintnull消费者限流大小
$prefetchCountint1消费者限流数量
$nonBlockingboolfalse是否是阻塞的
$timeOutint0超时时间
send

发送MQ消息(事务)

// @throws UtilException
$MQ->send( string $message, string $chanName, array $params, string $messageId = "auto" )
参数
参数必填类型描述
$messagearray参数
$chanNamearray参数
$messageIdarray参数
参数内容类型描述
messagestring消息
chanNamestring队列名
messageIdstring
listen

监听队列消息封装

// @throws UtilException
$mq->listen( [ 'chanName' => "Erp_ImportGoods" ], function ( AMQPMessage $msg ) {
  $body = $msg->getBody();
  var_dump($body);
  $msg->getChannel()->basic_ack( $msg->getDeliveryTag() );
});
参数
参数类型描述
$paramsarray参数 chanName args
$callbackfunctionamqp消息回调
close

关闭MQConn 关闭MQChan

// @throws UtilException
$mq->close();

MYSQLPDO

参考文档 medoo

继承 simpleHandle\Component\UtilPdo\BasePdo 类

use simpleHandle\Component\UtilPdo\BasePdo;
class DB extends BasePdo
{
	/**
	 * @throws UtilException
	 */
	public function __construct() {
		$dbConfig = [
      'host'       => '127.0.0.1',
      'port'       => 3306,
      'username'   => 'root',
      'password'   => 'root',
      'database'   => 'databasename',
      'charset'    => 'utf8mb4',
      'unixSocket' => null,
      'options'    => [
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      ],
      'size'       => 64
    ];
		parent::__construct( $dbConfig );
	}
}
$db = new DB();
配置
配置项必填类型配置值
hoststring127.0.0.1
portint3306
usernamestringroot
passwordstringroot
databasestringdatabasename
charsetstringutf8mb4
unixSocketNull空即可
optionsarray用于链接
sizeint64

Redis

参考文档 swoole redis 客户端

继承 simpleHandle\Component\UtilRedis\BaseRedis 类

use simpleHandle\Component\UtilRedis\BaseRedis;
class REDIS extends BaseRedis
{
	/**
	 * @throws UtilException
	 */
	public function __construct() {
		$redisConfig = [
      'host'     => '47.100.226.141',       // Redis服务器
      'port'     => 58878,                   // Redis端口
      'auth'     => "Zn4419268.",           // Redis密码
      'db_index' => 1,                      // Redis库序号
      'timeout'  => 3.0,                    // 连接超时
      'size'     => 10,                     // 客户端异常重连次数
    ];
		parent::__construct( $redisConfig );
	}
}
$db = new DB();
配置
配置项必填类型配置值
hoststring127.0.0.1
portint3306
authstringrequirepass
db_indexstring1
timeoutstring3.0
sizestring10

Log

继承 simpleHandle\Component\UtilLog\Logger 类

use simpleHandle\Component\UtilLog\Logger;
class Log extends Logger
{
	/**
	 * @throws Exception
	 * @throws UtilException
	 */
	public function __construct( string $fileName, bool $output = false ) {
		$loggerPath = ROOT . DIRECTORY_SEPARATOR . 'Log';
		$fileLock   = ROOT . DIRECTORY_SEPARATOR . 'composer.json';
		parent::__construct( $fileName, $loggerPath, $output, $fileLock );
	}
}
$log = new Log("logfile");
配置
配置项必填类型描述
$fileNamestring文件名
$loggerPathstring日志文件根路径
$outputbool时候输出到控制台
$fileLockstring文件锁(文件路径) 【并发会导致创建文件异常报错导致日志记录失败,如有多个进程写日志需设定该参数】
示例
$log->appendLog("hello"); // 拼接日志
$log->appendLog("world"); // 拼接日志
$log->write();// 日志写入到文件
/*
【2022-01-17 14:32:52】【INFO】hello
【2022-01-17 14:32:52】【INFO】world
*/

$log->appendLog("hello"); // 拼接日志
$log->writeLog("world");// 日志写入到文件
/*
【2022-01-17 14:32:52】【INFO】hello
【2022-01-17 14:32:52】【INFO】world
*/

$log->writeLine("hello",Logger::INFO);
// 【2022-01-17 14:32:52】【INFO】hello

/* 
Logger::SUCCESS
Logger::INFO
Logger::WARNING
Logger::ERROR
Logger::CRITICAL
Logger::DEBUG
*/
$log->success("hello");
$log->info("hello");
$log->warning("hello");
$log->error("hello");
$log->critical("hello");
$log->debug("hello");

Xls

参考文档 Xlswirte

参考代码注释

Tool

参考代码注释

参与贡献

  1. php-amqplib/php-amqplib
  2. godruoyi/php-snowflake
  3. inhere/php-validate
  4. ext-redis
  5. ext-pdo
  6. ext-json
  7. ext-xlswriter
  8. voku/anti-xss