可以在App Engine的app.yaml文件中指定VPC访问连接器。此外,为了确保应用程序中的所有出站流量都通过该连接器进行路由,需要在应用程序代码中使用socket API。
以下是一个基本示例:
app.yaml:
vpc_access_connector:
name: projects/[PROJECT-ID]/locations/[REGION]/connectors/[CONNECTOR-NAME]
egress_setting: ALL_TRAFFIC
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: .*
script: main.app
代码:
import socket
# Use the connect() method to route all outbound traffic through the VPC access connector socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect(('httpbin.org', 80))
# Send a HTTP request through the socket socket.sendall(b'GET /ip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n')
response = socket.recv(1024)
print(response)
这将通过VPC访问连接器路由到httpbin.org,并输出该网站的IP地址。如果应用程序中使用的其他库也使用套接字进行出站连接,则会通过VPC连接器自动路由。