Pub/Sub 消息处理程序
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
用于处理 Cloud Pub/Sub 推送订阅递送的消息的服务。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[],[],null,["# Handler for Pub/Sub messages\n\nService to handle messages delivered by a Cloud Pub/Sub Push subscription.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Use Pub/Sub with Cloud Run tutorial](/run/docs/tutorials/pubsub)\n- [Using Pub/Sub with Knative serving](/anthos/run/archive/docs/tutorials/pubsub)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n app.MapPost(\"/\", (Envelope envelope) =\u003e\n {\n if (envelope?.Message?.Data == null)\n {\n app.Logger.LogWarning(\"Bad Request: Invalid Pub/Sub message format.\");\n return Results.BadRequest();\n }\n\n var data = Convert.FromBase64String(envelope.Message.Data);\n var target = System.Text.Encoding.UTF8.GetString(data);\n\n app.Logger.LogInformation($\"Hello {target}!\");\n\n return Results.NoContent();\n });\n\n### Go\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // WrappedMessage is the payload of a Pub/Sub event.\n //\n // For more information about receiving messages from a Pub/Sub event\n // see: https://cloud.google.com/pubsub/docs/push#receive_push\n type WrappedMessage struct {\n \tMessage struct {\n \t\tData []byte `json:\"data,omitempty\"`\n \t\tID string `json:\"id\"`\n \t} `json:\"message\"`\n \tSubscription string `json:\"subscription\"`\n }\n\n // HelloPubSub receives and processes a Pub/Sub push message.\n func HelloPubSub(w http.ResponseWriter, r *http.Request) {\n \tvar m WrappedMessage\n \tbody, err := io.ReadAll(r.Body)\n \tdefer r.Body.Close()\n \tif err != nil {\n \t\tlog.Printf(\"io.ReadAll: %v\", err)\n \t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n \t\treturn\n \t}\n \t// byte slice unmarshalling handles base64 decoding.\n \tif err := json.Unmarshal(body, &m); err != nil {\n \t\tlog.Printf(\"json.Unmarshal: %v\", err)\n \t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n \t\treturn\n \t}\n\n \tname := string(m.Message.Data)\n \tif name == \"\" {\n \t\tname = \"World\"\n \t}\n \tlog.Printf(\"Hello %s!\", name)\n }\n\n### Java\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.example.cloudrun.Body;\n import java.util.Base64;\n import org.apache.commons.lang3.StringUtils;\n import org.springframework.http.HttpStatus;\n import org.springframework.http.ResponseEntity;\n import org.springframework.web.bind.annotation.RequestBody;\n import org.springframework.web.bind.annotation.RequestMapping;\n import org.springframework.web.bind.annotation.RequestMethod;\n import org.springframework.web.bind.annotation.RestController;\n\n // PubsubController consumes a Pub/Sub message.\n @RestController\n public class PubSubController {\n @RequestMapping(value = \"/\", method = RequestMethod.POST)\n public ResponseEntity\u003cString\u003e receiveMessage(@RequestBody Body body) {\n // Get PubSub message from request body.\n Body.Message message = body.getMessage();\n if (message == null) {\n String msg = \"Bad Request: invalid Pub/Sub message format\";\n System.out.println(msg);\n return new ResponseEntity\u003c\u003e(msg, HttpStatus.BAD_REQUEST);\n }\n\n String data = message.getData();\n String target =\n !StringUtils.isEmpty(data) ? new String(Base64.getDecoder().decode(data)) : \"World\";\n String msg = \"Hello \" + target + \"!\";\n\n System.out.println(msg);\n return new ResponseEntity\u003c\u003e(msg, HttpStatus.OK);\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n app.post('/', (req, res) =\u003e {\n if (!req.body) {\n const msg = 'no Pub/Sub message received';\n console.error(`error: ${msg}`);\n res.status(400).send(`Bad Request: ${msg}`);\n return;\n }\n if (!req.body.message) {\n const msg = 'invalid Pub/Sub message format';\n console.error(`error: ${msg}`);\n res.status(400).send(`Bad Request: ${msg}`);\n return;\n }\n\n const pubSubMessage = req.body.message;\n const name = pubSubMessage.data\n ? Buffer.from(pubSubMessage.data, 'base64').toString().trim()\n : 'World';\n\n console.log(`Hello ${name}!`);\n res.status(204).send();\n });\n\n### Python\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n @app.route(\"/\", methods=[\"POST\"])\n def index():\n \"\"\"Receive and parse Pub/Sub messages.\"\"\"\n envelope = request.get_json()\n if not envelope:\n msg = \"no Pub/Sub message received\"\n print(f\"error: {msg}\")\n return f\"Bad Request: {msg}\", 400\n\n if not isinstance(envelope, dict) or \"message\" not in envelope:\n msg = \"invalid Pub/Sub message format\"\n print(f\"error: {msg}\")\n return f\"Bad Request: {msg}\", 400\n\n pubsub_message = envelope[\"message\"]\n\n name = \"World\"\n if isinstance(pubsub_message, dict) and \"data\" in pubsub_message:\n name = base64.b64decode(pubsub_message[\"data\"]).decode(\"utf-8\").strip()\n\n print(f\"Hello {name}!\")\n\n return (\"\", 204)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=cloudrun)."]]