Cloudmap是AWS的服务发现工具,假设我们已经有一个开发好的Lambda function,并且注册到了Cloudmap中,我们需要从PHP开发的服务中通过服务发现调用该Lambda,首先我们已知该服务注册的namespace以及service name,下面是实现过程:

  1. 首先用golang实现一个Lambda,并注册到Cloudmap,golang的逻辑就不赘述了,主要是如何注册到Cloudmap,假设namespace为my-namespace,service name为 my-service,下面是通过AWS的SAM部署Lambda function时,template.yaml文件的主要内容:
Resources:
  DemoFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: controllers/demo/
      Handler: main
      Runtime: go1.x
      Tracing: Active 
      Policies:
        - VPCAccessPolicy:
            Description: "Gives access to create, delete, describe and detach ENIs"
            Resource: "*"
      VpcConfig:
        SecurityGroupIds:
          - !Ref ParameterSecurityGroup
        SubnetIds:
          - !Ref ParameterSubNet1
          - !Ref ParameterSubNet2
  DemoNameSpace:
    Type: AWS::ServiceDiscovery::HttpNamespace
    Properties:
      Name: my-namespace
  DemoService:
    Type: AWS::ServiceDiscovery::Service
    Properties:
      Name: my-service
      NamespaceId: !Ref DemoNameSpace
  DemoInstance:
    Type: AWS::ServiceDiscovery::Instance
    Properties:
      InstanceAttributes:
        env: prod
      InstanceId: !Ref DemoFunction
      ServiceId: !Ref DemoService
  1. 通过composer引用AWS的PHP SDK
composer require aws/aws-sdk-php
  1. 开发php代码如下:
<?php
require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use Aws\Lambda\LambdaClient;
use Aws\ServiceDiscovery\ServiceDiscoveryClient;

$credentials = new Aws\Credentials\Credentials('access_key', 'access_secret');
$client = new Aws\ServiceDiscovery\ServiceDiscoveryClient([
    'version' => 'latest',
    'region' => 'ap-southeast-1',
    'credentials' => $credentials,
]);
$result = $client->discoverInstances([
    'NamespaceName' => 'my-namespace',
    'ServiceName' => 'my-service',
    'QueryParameters' => ['env' => 'prod'],
]);
$lambdaClient = new Aws\Lambda\LambdaClient([
    'version' => 'latest',
    'region' => 'ap-southeast-1',
    'credentials' => $credentials,
]);
$fn = $result['Instances'][0]["InstanceId"];
$res = $lambdaClient->invoke([
    "FunctionName" => $fn,
]);
print_r($res->get("Payload")->__toString())