ThinkPHP框架开发RPC接口

使用RPC方式开发应用,会使在网络分布式多程序内的应用程序更加容易。本文分享关于在ThinkPHP框架中如何开发RPC接口,我们可以通过继承PHPRpc来实现开发接口以及调用。

服务端代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

namespace Home\Controller;

 

use Think\Controller\RpcController;

 

class ServerController extends RpcController{

 

    protect $allowMethodList = array('test1','test2'); //表示只允许访问这两个方法

 

    public function test1(){

 

         return 'test1';

 

    }

 

    public function test2(){

 

         return 'test2';

 

    }

 

    private function test3(){

 

        return 'test3';

 

   }

 

   protected function test4(){

 

      return 'test3';

 

   }

 

}


客户端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

namespace Home\Controller;

 

use Think\Controller;

 

class IndexController extends Controller {

 

    public function index(){

 

        Vendor('phpRPC.phprpc_client');

 

        $client = new \PHPRPC_Client('http://serverName/index.php/Home/Server');

 

        // 或者采用

       //$client = new \PHPRPC_Client();

 

       //$client->useService('http://serverName/index.php/Home/Server');

       //调用服务端方法

       $result = $client->test1();

 

    }

 

}


评论 (0)

发表评论