分类 默认 下的文章

一、微服务安装
二、微服务配置
三、微服务接口设计
四、RESTful 权限
五、RESTful 速率设置
六、RESTful 注册及测试
七、状态码中文翻译

源代码:

micro-app.rar

学习Yii2微服务框架 实现一些基本功能 及案例

   'id' => 'micro-app',
    // the basePath of the application will be the `micro-app` directory
    'basePath' => __DIR__,
    // this is where the application will find all controllers
    'controllerNamespace' => 'micro\controllers',
    // set an alias to enable autoloading of classes from the 'micro' namespace
    'aliases' => [
        '@micro' => __DIR__,
    ],
    'language' => 'zh-CN',
    'components' => [
        //获取JSON数据
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        //配置自定义响应
        'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                    $response = $event->sender;
                    $code = $response->getStatusCode();
                    $msg = $response->statusText;
                    if ($code == 404) {
                        !empty($response->data['message']) && $msg = $response->data['message'];
                    }
                    //设置固定返回数据参数
                    $data = [
                        'code' => $code,
                        'msg' => $msg,
                        'data' => $response->data
                    ];
                    $code == 200 && $data['data'] = $response->data;
                    $response->data = $data;
                    $response->format = yii\web\Response::FORMAT_JSON;
            },
        ],
        //会员
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],
        //URL美化
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
               '' => 'site/index',
               ['class' => 'yii\rest\UrlRule', 'controller' => 'post','pluralize'=>false],
                
            ],
        ],
        //连接MYSQL数据库
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=micro',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
        ],
        'cookieValidationKey' => 'O1d232trde1xww-M97_7QvwPo-5QGdkLMp#@#@', 
    ],

以下为DEMO
micro-app.zip

根据Yii2【高级专题】安装restful接口开发时候,发现get/delete/patch等都可以,就唯独put协议无法更新内容

https://www.yiiframework.com/doc/guide/2.0/zh-cn/tutorial-yii-as-micro-framework

比如:

PUT http://micro.com/posts/1

这里是更新id=1的内容

本实例字段内容有id、title、body

如果没有下方添加rule规则的话,就被过滤了。看效果1

14.png

二、加完代码后就解决了

15.png

原来问题出在这里
19.png

tp5的queue服务安装,请参考composer 安装的方法!这里不再累述。本文主要是针对开发【开启服务】和【关闭服务】

本文仅支持在linux上使用。

根据linux的脚本实例,如:

kill -9 11340;
kill -9 8825;

linux多命令的执行使用英文;隔开。这个就为关闭多个queue服务提供了条件。

设计思路:

一、创建进程,写入进程号【开启服务】

队列: OrderUnPay ---对未支付的订单进行延时作废。

脚本命令如下:

"cd /www/wwwroot/saas.com/; php think queue:work --queue OrderUnPay --daemon > /dev/null 2> /dev/null & echo true"

php exec 执行以上linux脚本后。

使用命令

ps -aux | grep queue

810.png

可以看到里面的15865进程ID

那么如何才能将这个进程ID 15862输出,并写入数据库,方便后面的【关闭服务】

ps -aux|grep OrderUnPay |awk '{print $2}' | head -1

可以使用以上这个命令,通过关键词搜索,并倒序拿出当前的结果

以下php代码,进程ID就可以通过$out[0]

$pid_sq="ps -aux|grep OrderUnPay |awk '{print $2}' | head -1";
$process=exec($pid_sq,$out);
$process_id=isset($out[0])?$out[0]:0;

二.使用多个kill -9 制作【关闭服务】

kill -9 15862;

kill -9 ....;


以下是我tp下的【单个开启服务】和【关闭全部服务】功能

    #关闭服务
public function closed(){
     $out=array();
     $message='关闭服务失败!';
     $output='';
    if(strpos(PHP_OS,"Linux")!==false){
      #Linux套字
      $map['process_id']=array('gt',0);
      $process_ids=$this->model->where($map)->column('process_id');
      if(!empty($process_ids)){
          $exec_power ='';
        foreach($process_ids as $k=>$v){
           $exec_power .="kill -9 ".$v." ;"; 
        }
        $exec_power .=" echo true";
        #exit($exec_power);
        $message = exec($exec_power,$output, $ret);
      }else{
        $message ='没有进程数据';
      }
      
      #$exec_power ="kill -s 9 `ps -aux | grep queue| grep -v grep | awk '{print $2}'` & echo true";
    }else if(strpos(PHP_OS,"WIN")!==false){
      #Win套字
      $exec_power ='cd /d 2>&1'. ROOT_PATH .' & php think queue:restart';
      $message = exec($exec_power,$output, $ret);
    }else{
      $this->error('未识别的操作系统');
    }
    #命令执行
    #$message = shell_exec($exec_power);

    if(count($output)>0){
      foreach($output as $k=>$v){
        $info=iconv('GB2312', 'UTF-8',$v);
        $out[$k]=$info;
        $message.=$info;
      }
    }
    #返回结果
    if(!$ret){    
      $this->model->where(array('status'=>1))->update(['work_status'=>0,'process_id'=>0]);
      $this->success('关闭服务成功','',$exec_power);
    }else{
       $this->error($message,'');
    }
}
    #启动服务
public function powers(){
     $id =$this->request->param('id');
     $info=$this->model->where(array('id'=>$id))->find();
     $daemon =1;
     #获取标识
     $job_code =$info['job_code'];
     if(!empty($job_code)){
       #判断win还是linux
       if(strpos(PHP_OS,"Linux")!==false){
             #Linux套字
             if($daemon){
             $exec_power ='cd '. ROOT_PATH .'; php think queue:work --queue ' .$job_code.' --daemon > /dev/null 2> /dev/null & echo true';
             }else{
             $exec_power ='cd '. ROOT_PATH .'; php think queue:work --queue ' .$job_code.' & echo true';
             }
        }else if(strpos(PHP_OS,"WIN")!==false){
             #Win套字
             if($daemon){
               $exec_power ='cd /d '. ROOT_PATH .' & start /B php think queue:work --queue ' .$job_code.' --daemon'.' & echo true';
             }else{
               $exec_power ='cd /d "'. ROOT_PATH .'" & php think queue:work --queue ' .$job_code.' & echo true';
             }
        }else{
          $this->error('未识别的操作系统');
        }

        #命令执行
        $message ='';
        $process_id='';
        if($daemon>0){
            if(strpos(PHP_OS,"WIN")!==false){
            #打开一个进程
            $win_pid =popen($exec_power, 'r');
            $ret =fgets($win_pid);
            pclose($win_pid); #对应的是int(1) 
            }else{
            #执行命令
             $ret = shell_exec($exec_power);
             #查看进程
              $pid_sq ="ps -aux|grep $job_code |awk '{print $2}' | head -1";
              $process=exec($pid_sq,$out);
              $process_id=isset($out[0])?$out[0]:0;
            }
        }else{
         $ret = shell_exec($exec_power);
        }
        #获取进程ID
        $process_id=$process_id>0?$process_id:'';
        if($ret){
           $this->model->where(array('id'=>$id))->update(['work_status'=>1,'process_id'=>$process_id]);
           $this->success('启动成功','',$exec_power);    
        }else{
           $this->error('启动失败','',$exec_power);
        }
     }else{
        $this->error('未找到对应的任务标识');
     }
}

最近在使用fastadmin框架(tp5.1)实现后台的基本功能,在selectpage需要显示更多信息,根据文档信息进行改造实现以下功能:

A-1.png

分别在控制器、以及view文件进行改造。

controller 控制器代码部分

#增加显示更多字段
protected $selectpageFields = "id,batch_number,coupons_date,coupons_money,coupons_remain";

View 视图部分 本实例在add.html

                <div class="col-xs-12 col-sm-8">
                    <input id="c-batch_number" data-rule="required" data-source="Batch/selectpage" class="form-control selectpage" name="row[batch_number]" type="text" value="" data-primary-key="batch_number" data-field="batch_number" data-format-item="{batch_number}-(有效期:{coupons_date}-剩余:{coupons_remain})">
                </div>

记录之,方便后期使用。

如出现乱码,请以utf-8文件编码保存