5. 修改解析规则:
(1). 是否所有服务需要验证:
①. 并不是所有服务都需要token认证,分几种情况:
a. 必须要token
b. 可有可无.如获取最新的新闻、课程数据.
②. 在rpc服务中使用consul-tag来进行配置:
"gw.tokenValid.ICourse=get",
"gw.tokenValid.ICourse=list",
a. 表示请求/ICourse/get方法、/ICourse/list方法均需要token认证.
③. 尽量让业务端、RPC服务端只要改tag就可以,不需要做特殊的配置.
a. 把公共的部分全部放到gateway中.
b. 不要在每个业务接口都写一个公共方法.
(2). 分析需要的解析结果:
①. 获取consul_tag:
array(7) {
[0] => string(9) "order_rpc"
[1] => string(24) "gw.NAMESPACE=App.Rpc.Lib"
// 键为rateLimiter对应一个一唯关连数组:['key' => x, 'rate' => x, 'max' => x]
[2] => string(24) "gw.rateLimiter.key=order"
[3] => string(21) "gw.rateLimiter.rate=1"
[4] => string(20) "gw.rateLimiter.max=1"
// 键为tokenValid对应一个二唯数组:['ICourse' => [get, list]]
[5] => string(25) "gw.tokenValid.ICourse=get"
[6] => string(26) "gw.tokenValid.ICourse=list"
}
②. 需要解析的结果:
array(3) {
["NAMESPACE"] => string(11) "App\Rpc\Lib"
["rateLimiter"] =>
array(3) {
["key"] => string(5) "order"
["rate"] => string(1) "1"
["max"] => string(1) "1"
}
["tokenValid"] =>
array(1) {
["ICourse"] =>
array(2) {
[0] => string(3) "get"
[1] => string(4) "list"
}
}
}
(3). app\Lib\ServiceHelper.php:
namespace App\Lib;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Agent;
use Swoft\Consul\Health;
/**
* @Bean()
*/
class ServiceHelper{
...
// 解析tags
public function parseTags(array $service): array
{
if (empty($service) || !is_array($service) || empty($service['Tags'])) {
return [];
}
$result = [];
foreach ($service['Tags'] as $v) {
// 二段式解析:gw.NAMESPACE=App.Rpc.Lib
if (preg_match("/^gw\.(\w+)=(.*)/i", $v, $matches)) {
$result[$matches[1]] = str_replace('.', '\\', $matches[2]);
continue;
}
// 三段式解析:gw.rateLimiter.key=order
// ['rateLimiter' => ['key' => 'xx', 'rate' => 0, 'max' => 0]]
if (preg_match("/^gw\.(\w+).(\w+)=(.*)/i", $v, $matches)) {
// 检查$result是否有这个key,没有则赋值一个空数组.
if (!isset($result[$matches[1]])) {
$result[$matches[1]] = [];
}
// $result[$matches[1]][$matches[2]] = $matches[3];
$getTagValue = str_replace(".", "\\", $matches[3]);
if (isset($result[$matches[1]][$matches[2]])) {
if (is_array($result[$matches[1]][$matches[2]])) {
$result[$matches[1]][$matches[2]][] = $getTagValue;
} else {
$old = $result[$matches[1]][$matches[2]];
$result[$matches[1]][$matches[2]] = [$old, $getTagValue];
}
} else {
$result[$matches[1]][$matches[2]] = $getTagValue;
}
}
}
return $result;
}
}