swoole_exmple/Server/http.php
Wenbin.Wang 1be654dd5f 代码
2021-12-24 16:44:53 +08:00

186 lines
5.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Http服务端类
* User: fantasticbin
* Date: 2020/1/15
*/
class Http
{
const HOST = '0.0.0.0';
const PORT = 8080;
protected $read_num = null;
public $server = null;
public function __construct()
{
// 创建Http服务器监听本机的所有地址并监听 8080 端口
$this->server = new Swoole\Http\Server(self::HOST, self::PORT);
// 设置响应html文件模式以及定义路径
$this->server->set([
'worker_num' => 2,
'enable_static_handler' => true,
'document_root' => dirname(dirname(__FILE__)) . '/Template'
]);
// 设置异步AIO线程数量
swoole_async_set([
'thread_num' => 10,
]);
// 监听启动
$this->server->on('Start', [$this, 'onStart']);
// 监听请求并输出内容
$this->server->on('Request', [$this, 'onRequest']);
}
/**
* 监听启动,修改主进程名称,便于执行平滑重启
*/
public function onStart()
{
swoole_set_process_name('http_server');
}
/**
* 监听请求并输出内容
* @param $request object 请求对象
* @param $response object 响应对象
*/
public function onRequest($request, $response)
{
// 优化请求,防止图标再次请求浪费资源
if ($request->server['request_uri'] == '/favicon.ico') {
$response->status(404);
$response->end();
return ;
}
$get = json_encode($request->get);
$html = <<<EOT
<h1>Hello Swoole.</h1>
<h2>The get request is {$get}</h2>
EOT;
// 记录访问日志
$log = [
'time' => date('Y-m-d H:i:s'),
'get' => $request->get,
'post' => $request->post,
'header' => $request->header
];
if (!is_dir(__DIR__ . '/log')) {
mkdir(__DIR__ . '/log');
}
Swoole\Async::writeFile(__DIR__ . '/log/access.log', json_encode($log) . PHP_EOL, function($filename) {}, FILE_APPEND);
// 在MySQL数据库中增加访问量
$this->addReadNum();
// 读取redis里的访问量数据如无则从常量中定义
$this->getReadNum();
// 设置响应头信息
$response->header('Content-Type', 'text/html; charset=utf-8');
// 设置cookie信息
$response->cookie('code', 'Hello world', time() + 1800);
// 输出显示内容
$response->end($html);
}
/**
* 增加访问量方法
*/
public function addReadNum()
{
$update_db = new Swoole\Coroutine\MySQL();
$select_db = new Swoole\Coroutine\MySQL();
$config = [
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'swoole',
'password' => 'Zhang1994)!)(',
'database' => 'swoole',
'charset' => 'utf8mb4',
'timeout' => 2
];
// 进行MySQL数据库连接
$conn_res = $select_db->connect($config);
if ($conn_res === false) {
echo 'MySQL connect error!' . PHP_EOL;
var_dump($select_db->connect_errno, $select_db->connect_error) . PHP_EOL;
throw new Swoole\ExitException('program exit.');
}
// 获取到访问量的数据
$result = $select_db->query('SELECT read_num FROM test WHERE id = 1');
if ($result !== false) {
if (isset($result[0]['read_num'])) $this->read_num = $result[0]['read_num'];
echo 'MySQL execute success, data: ' . PHP_EOL;
var_dump($result);
}
// 一定要记得关闭MySQL连接
$select_db->close();
// 进行MySQL数据库连接这里是并发再开启一个MySQL连接进程
$conn_res = $update_db->connect($config);
if ($conn_res === false) {
echo 'MySQL connect error!' . PHP_EOL;
var_dump($update_db->connect_errno, $update_db->connect_error) . PHP_EOL;
throw new Swoole\ExitException('program exit.');
}
// 执行增加访问量的语句并处理结果
$result = $update_db->query('UPDATE test SET read_num = read_num + 1 WHERE id = 1');
if ($result !== false) {
echo 'MySQL execute success, affected rows: ' . $update_db->affected_rows . ', insert id: ' . $update_db->insert_id . PHP_EOL;
}
// 一定要记得关闭MySQL连接
$update_db->close();
}
/**
* 读取redis里的访问量数据如无则从常量中定义
*/
public function getReadNum()
{
$redis = new Swoole\Coroutine\Redis();
$redis->connect('127.0.0.1', 6379);
$read_num = $redis->get('read_num');
if (empty($read_num)) {
if (!isset($this->read_num)) {
throw new Swoole\ExitException('Read num not exist!');
}
$read_num = $this->read_num;
$redis->set('read_num', $read_num);
echo 'The data from MySQL.' . PHP_EOL;
} else {
echo 'The data from Redis.' . PHP_EOL;
}
echo "The redis read num is: {$read_num}";
}
/**
* 启动Http服务器
*/
public function start()
{
$this->server->start();
}
}
$http = new Http();
$http->start();