关于其中的io操作,具体查看手册。
下面给出两个小例子:
<?php
/**
* Created by PhpStorm.
* User: season
* Date: 18-4-4
* Time: 下午2:03
*/
//命名空间风格
Swoole\Async::readfile(__DIR__.'/1.txt', function ($filename,$fileConetnt) {
echo 'filename:'.$filename.PHP_EOL;
echo 'content:'.$fileConetnt.PHP_EOL;
});
echo 'start'.PHP_EOL;
<?php
/**
* Created by PhpStorm.
* User: season
* Date: 18-4-4
* Time: 下午2:03
*/
$content = date('Y-m-d H:i:s').PHP_EOL;
//写文件 覆盖
//Swoole\Async::writeFile(__DIR__.'/1.txt',$content, function ($filename) {
// echo 'filename:'.$filename.PHP_EOL;
//});
//追加
Swoole\Async::writeFile(__DIR__.'/1.txt',$content, function ($filename) {
echo 'filename:'.$filename.PHP_EOL;
},FILE_APPEND);
echo 'start'.PHP_EOL;
Redis操作
前置条件
redis服务
hiredis库
编译安装swoole需要加入 -enable-async-redis
1.安装redis
首先去官网下载最新的包(我这边下载的4.0.10)并解压
image.png
season@ubuntu:/opt/redis-4.0.10$ make
season@ubuntu:/opt/redis-4.0.10$ cd src
season@ubuntu:/opt/redis-4.0.10/src$ ./redis-server
开启成功,端口6379
可以通过cli连接redis
season@ubuntu:/opt/redis-4.0.10/src$ ./redis-cli
127.0.0.1:6379>
2.安装redis服务
https://github.com/redis/hiredis/releases
下载后解压并进入
season@ubuntu:/opt/hiredis-0.13.3$ make
season@ubuntu:/opt/hiredis-0.13.3$ sudo make install
season@ubuntu:/opt/hiredis-0.13.3$ sudo ldconfig
安装成功
3.重新编译swoole
php环境安装在/usr/local/php/bin
image.png
./configure --with-php-config=/usr/local/php/bin/php-config --enable-async-redis
清空上次make所产生的文件
season@ubuntu:~/Downloads/swoole$ make clean
season@ubuntu:~/Downloads/swoole$ make -j
season@ubuntu:~/Downloads/swoole$ sudo make install
输出
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20170718/
Installing header files:
查看是否安装成功可以使用 php -m 查看是否有swoole
查看swoole是否支持异步redis
image.png
在swoole中使用异步resid的demo
<?php
/**
* Created by PhpStorm.
* User: season
* Date: 18-7-20
* Time: 下午2:03
*/
$redisClient = new Swoole\Redis();
/**
* $redisCli Swoole\Redis();
* $result redis connect 的返回值
*/
$redisClient->connect('127.0.0.1',6379,function (swoole_redis $swoole_redis ,$result){
echo 'connet'.PHP_EOL;
var_dump($result);
/**
* redis 设置key
* 参数1. key
* 参数2. value
* 参数3. 回调 $swoole_redis Swoole\Redis()对象; $result redis执行set的返回值
*/
$swoole_redis->set('season',time(),function (swoole_redis $swoole_redis,$result){
var_dump($result);
});
/**
* redis 根据key得到值
* 参数1. key
* 参数2. value
* 参数3. 回调 $swoole_redis Swoole\Redis()对象; $result redis执行set的返回值
*/
$swoole_redis->get('season',function (swoole_redis $swoole_redis ,$result){
var_dump($result);
});
/**
* redis 获取所有keys
* 参数1. *
* 参数2. value
* 参数3. 回调 $swoole_redis Swoole\Redis()对象; $result redis执行set的返回值
*/
$swoole_redis->keys('*',function (swoole_redis $swoole_redis,$result){
var_dump($result);
});
//模糊匹配
$swoole_redis->keys('sea*',function (swoole_redis $swoole_redis,$result){
var_dump($result);
});
});
网友评论