用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# 使用Google Cloud Pub / Sub进行消息传递 本指南将引导您逐步完成使用 在程序的不同部分之间或不同程序之间交换消息的过程 [Spring Integration通道适配器](https://docs.spring.io/spring-integration/reference/htmlsingle/#overview-endpoints-channeladapter) 和 [Google Cloud Pub / Sub](https://cloud.google.com/pubsub/) 作为底层消息交换机制 。 ## 你会建立什么 一个 [Spring Boot](https://spring.io/guides/gs/spring-boot/) Web应用程序,它向自身发送消息并处理这些消息。 ## 你需要什么 * 约15分钟 * 最喜欢的文本编辑器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您还可以将代码直接导入到IDE中: * [弹簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) * [启用了结算和发布/订阅的Google Cloud Platform项目](https://cloud.google.com/pubsub/docs/quickstart-console) * [Google Cloud SDK](https://cloud.google.com/sdk/) ## 如何完成本指南 像大多数Spring 一样 [入门指南](https://spring.io/guides) ,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。 无论哪种方式,您最终都可以使用代码。 要 **从头开始** ,请继续 [使用Gradle构建](https://spring.io/guides/gs/messaging-gcp-pubsub/#scratch) 。 要 **跳过基础知识** ,请执行以下操作: * [下载](https://github.com/spring-guides/gs-messaging-gcp-pubsub/archive/master.zip) 并解压缩本指南的源存储库,或使用 对其进行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-messaging-gcp-pubsub.git](https://github.com/spring-guides/gs-messaging-gcp-pubsub.git)` * 光盘进入 `gs-messaging-gcp-pubsub/initial` * 继续 [添加所需的依赖项](https://spring.io/guides/gs/messaging-gcp-pubsub/#initial) 。 **完成后** ,您可以根据中的代码检查结果 `gs-messaging-gcp-pubsub/complete`. ## 用Gradle构建 ## 用Maven编译 ## 使用您的IDE进行构建 ## 添加所需的依赖项 将以下内容添加到您的 `pom.xml` 文件,如果您使用的是Maven: ~~~ <dependencies> ... <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-gcp-starter-pubsub</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-core</artifactId> </dependency> ... </dependencies> ~~~ 或者,如果您使用的是Gradle: ~~~ dependencies { ... compile("org.springframework.cloud:spring-cloud-gcp-starter-pubsub:1.2.5.RELEASE") compile("org.springframework.integration:spring-integration-core") ... } ~~~ 如果您使用的是Maven,还强烈建议您使用Spring Cloud GCP物料清单来控制依赖项的版本: ~~~ <properties> ... <spring-cloud-gcp.version>1.2.5.RELEASE</spring-cloud-gcp.version> ... </properties> <dependencyManagement> <dependencies> ... <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-gcp-dependencies</artifactId> <version>${spring-cloud-gcp.version}</version> <type>pom</type> <scope>import</scope> </dependency> ... </dependencies> </dependencyManagement> ~~~ ## 设置Google Cloud Pub / Sub环境 您需要一个主题和一个订阅,才能从Google Cloud Pub / Sub发送和接收消息。 您可以在 创建它们,也可以 [Google Cloud Console中](https://console.cloud.google.com/cloudpubsub) 使用 `PubSubAdmin` 班级。 在本练习中,创建一个名为“ testTopic”的主题,并为该主题创建一个名为“ testSubscription”的订阅。 ## 创建应用程序文件 您将需要一个类来包括通道适配器和消息传递配置。 与Spring Boot应用程序一样,使用@SpringBootApplication标头创建PubSubApplication类。 `src/main/java/hello/PubSubApplication.java` ~~~ @SpringBootApplication public class PubSubApplication { public static void main(String[] args) throws IOException { SpringApplication.run(PubSubApplication.class, args); } } ~~~ 此外,由于您正在构建Web应用程序,因此请创建WebAppController类以在控制器和配置逻辑之间进行分隔。 `src/main/java/hello/WebAppController.java` ~~~ @RestController public class WebAppController { } ~~~ 我们仍然缺少HTML和属性的两个文件。 `src/main/resources/static/index.html` ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spring Integration GCP sample</title> </head> <body> <div name="formDiv"> <form action="/publishMessage" method="post"> Publish message: <input type="text" name="message" /> <input type="submit" value="Publish!"/> </form> </div> </body> </html> ~~~ `src/main/resources/application.properties` ~~~ #spring.cloud.gcp.project-id=[YOUR_GCP_PROJECT_ID_HERE] #spring.cloud.gcp.credentials.location=file:[LOCAL_FS_CREDENTIALS_PATH] ~~~ Spring Cloud GCP Core Boot启动器可以自动配置这两个属性并使它们成为可选属性。 属性文件中的属性始终优先于Spring Boot配置。 Spring Cloud GCP Core Boot启动器与Spring Cloud GCP Pub / Sub Boot启动器捆绑在一起。 GCP项目ID是通过以下方式自动配置的: `GOOGLE_CLOUD_PROJECT`环境变量 [等](https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java#L287) 。 OAuth2凭据是通过 自动配置的 [GOOGLE\_APPLICATION\_CREDENTIALS](https://developers.google.com/identity/protocols/application-default-credentials) 环境变量 。 如果 了 [Google Cloud SDK](https://cloud.google.com/sdk/) 安装 ,则可以通过运行 `gcloud auth application-default login`在与应用相同的过程中(或在父过程中)命令。 ## 创建入站通道适配器 入站通道适配器侦听来自Google Cloud Pub / Sub订阅的消息,并将其发送到应用程序中的Spring通道。 实例化入站通道适配器需要一个 `PubSubTemplate` 实例和现有订阅的名称。 `PubSubTemplate`是Spring订阅Google Cloud Pub / Sub主题的抽象。 Spring Cloud GCP发布/订阅启动启动器提供了自动配置的 `PubSubTemplate` 您可以简单地将其作为方法参数注入的实例。 `src/main/java/hello/PubSubApplication.java` ~~~ @Bean public PubSubInboundChannelAdapter messageChannelAdapter( @Qualifier("pubsubInputChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) { PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, "testSubscription"); adapter.setOutputChannel(inputChannel); adapter.setAckMode(AckMode.MANUAL); return adapter; } ~~~ 默认情况下,消息确认模式在适配器中设置为自动。 如示例所示,此行为可能会被覆盖。 实例化通道适配器后,必须配置适配器将接收到的消息发送到的输出通道。 `src/main/java/hello/PubSubApplication.java` ~~~ @Bean public MessageChannel pubsubInputChannel() { return new DirectChannel(); } ~~~ 连接到入站通道的是服务激活器,用于处理传入消息。 `src/main/java/hello/PubSubApplication.java` ~~~ @Bean @ServiceActivator(inputChannel = "pubsubInputChannel") public MessageHandler messageReceiver() { return message -> { LOGGER.info("Message arrived! Payload: " + new String((byte[]) message.getPayload())); BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class); originalMessage.ack(); }; } ~~~ 这 `ServiceActivator` 输入频道名称(例如, `"pubsubInputChannel"`)必须与输入通道方法名称匹配。 每当有新消息到达该通道时,返回的消息都会对其进行处理 `MessageHandler`. 在此示例中,仅通过记录其正文并确认该消息即可对其进行处理。 在手动确认中,使用 `BasicAcknowledgeablePubsubMessage` 对象,该对象附加到 `Message` 标头,可以使用 `GcpPubSubHeaders.ORIGINAL_MESSAGE` 钥匙。 ## 创建一个出站通道适配器 出站通道适配器侦听来自Spring通道的新消息,并将其发布到Google Cloud Pub / Sub主题。 实例化出站通道适配器需要一个 `PubSubTemplate` 以及现有主题的名称。 `PubSubTemplate`是Spring的抽象概念,用于将消息发布到Google Cloud Pub / Sub主题。 Spring Cloud GCP发布/订阅启动启动器提供了自动配置的 `PubSubTemplate`实例。 `src/main/java/hello/PubSubApplication.java` ~~~ @Bean @ServiceActivator(inputChannel = "pubsubOutputChannel") public MessageHandler messageSender(PubSubTemplate pubsubTemplate) { return new PubSubMessageHandler(pubsubTemplate, "testTopic"); } ~~~ 您可以使用 `MessageGateway` 将消息写入频道并将其发布到Google Cloud Pub / Sub。 `src/main/java/hello/PubSubApplication.java` ~~~ @MessagingGateway(defaultRequestChannel = "pubsubOutputChannel") public interface PubsubOutboundGateway { void sendToPubsub(String text); } ~~~ 通过此代码,Spring自动生成一个对象,然后可以将该对象自动连接到应用程序的私有字段中。 `src/main/java/hello/WebAppController.java` ~~~ @Autowired private PubsubOutboundGateway messagingGateway; ~~~ ## 添加控制器逻辑 向控制器添加逻辑,使您可以写入Spring通道: `src/main/java/hello/WebAppController.java` ~~~ package hello; import hello.PubSubApplication.PubsubOutboundGateway; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.view.RedirectView; @RestController public class WebAppController { // tag::autowireGateway[] @Autowired private PubsubOutboundGateway messagingGateway; // end::autowireGateway[] @PostMapping("/publishMessage") public RedirectView publishMessage(@RequestParam("message") String message) { messagingGateway.sendToPubsub(message); return new RedirectView("/"); } } ~~~ ## 验证 您的应用程序必须通过GOOGLE\_APPLICATION\_CREDENTIALS环境变量或通过 `spring.cloud.gcp.credentials.location` 财产。 如果您安装了 [Google Cloud SDK](https://cloud.google.com/sdk/) ,则可以使用 `gcloud auth application-default login` 命令。 或者,您可以从 下载服务帐户凭据文件, [Google Cloud Console](https://cloud.google.com/console) 然后将其指向 `spring.cloud.gcp.credentials.location` 物业 `application.properties` 归档到它。 作为 [春季资源](https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/resources.html) , `spring.cloud.gcp.credentials.location` 也可以从文件系统以外的其他位置获得,例如URL,类路径等。 ## 使应用程序可执行 尽管可以将该服务打包为传统的 [WAR](https://spring.io/understanding/WAR) 文件以部署到外部应用程序服务器,但是下面演示的更简单的方法创建了一个独立的应用程序。 您将所有内容打包到一个由Java驱动的单个可执行JAR文件中 `main()`方法。 另外,您使用Spring的支持将 嵌入 [Tomcat](https://spring.io/understanding/Tomcat) servlet容器作为HTTP运行时 ,而不是部署到外部实例。 `@SpringBootApplication` 是一个方便注释,它添加了以下所有内容: * `@Configuration`:将类标记为应用程序上下文的Bean定义的源。 * `@EnableAutoConfiguration`:告诉Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。 例如,如果 `spring-webmvc` 在类路径上,此注释将应用程序标记为Web应用程序并激活关键行为,例如设置 `DispatcherServlet`. * `@ComponentScan`:告诉Spring在服务器中寻找其他组件,配置和服务 `hello` 包,让它找到控制器。 这 `main()` 方法使用Spring Boot的 `SpringApplication.run()`启动应用程序的方法。 您是否注意到没有一行XML? 没有 `web.xml`文件。 该Web应用程序是100%纯Java,因此您无需处理任何管道或基础结构。 ### 建立可执行的JAR 您可以使用Gradle或Maven从命令行运行该应用程序。 您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。 生成可执行jar使得在整个开发生命周期中,跨不同环境等等的情况下,都可以轻松地将服务作为应用程序进行发布,版本控制和部署。 如果您使用Gradle,则可以通过使用以下命令运行该应用程序 `./gradlew bootRun`。 或者,您可以通过使用以下命令构建JAR文件: `./gradlew build` 然后运行JAR文件,如下所示: ~~~ java -jar build/libs/gs-messaging-gcp-pubsub-0.1.0.jar ~~~ 如果您使用Maven,则可以通过使用以下命令运行该应用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令构建JAR文件: `./mvnw clean package` 然后运行JAR文件,如下所示: ~~~ java -jar target/gs-messaging-gcp-pubsub-0.1.0.jar ~~~ 此处描述的步骤将创建可运行的JAR。 您还可以 构建经典的WAR文件 。 显示日志记录输出。 该服务应在几秒钟内启动并运行。 ## 测试应用程序 现在该应用程序正在运行,您可以对其进行测试。 打开 [http:// localhost:8080](http://localhost:8080) ,在输入文本框中键入一条消息,然后按“发布!” 按钮并确认消息已正确记录在您的过程终端窗口中。 ## 概括 恭喜你! 您刚刚开发了一个Spring应用程序,该应用程序使用Spring Integration GCP发布/订阅通道适配器来交换消息!