微服务之间通讯主要有两种方式Restful Api
和Rpc
,本文主要聊一聊他们的区别。php
这些列子是基于one的 (一个极简 . 高性能 . 松耦合 . 分布式框架 ) github.com/lizhichao/o… 欢迎你们star。git
Restful Api
实现:Router::get('/article/{id}','ArticleController@get');
Router::post('/article','ArticleController@create');
Router::put('/article/{id}','ArticleController@edit');
Router::delete('/article/{id}','ArticleController@delete');
复制代码
而后在控制器ArticleController
调用模型实现对数据的操做。github
// get
return Article::find($id)->toArray();
// 其余增删改...
复制代码
Rpc
实现RpcServer::add('Article');
复制代码
没错就一行代码就能够了,这里是把这个模型共享出去了,客户端只用模型能够实现任意操做。框架
假如机器A上面一个计算器 Counter
,以Rpc的方式提供给其余机器使用.分布式
计算器Counter
代码微服务
class Counter {
private $i = 0;
public function __construct($i = 0) {
$this->i = $i;
}
// 加法
public function add($v) {
$this->i += $v;
return $this;
}
// 减法
public function sub($v) {
$this->i -= $v;
return $this;
}
// 乘法
public function mul($v) {
$this->i *= $v;
return $this;
}
// 除法
public function div($v) {
$this->i /= $v;
return $this;
}
// 获取结果
public function get() {
return $this->i;
}
}
复制代码
Rpc
实现RpcServer::add('Counter');
复制代码
Rpc客户端调用post
$c = new ClientCounter(10);
echo $c->add(3)->mul(2)->sub(10)->div(5)->get();
复制代码
Restful Api
实现:你以为 Restful Api
应该怎么实现?性能