Spring Cloud 3.x 集成 Google Datastore快速入门DEMO

宁睿  金牌会员 | 2025-1-16 15:55:14 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 942|帖子 942|积分 2836

1. 介绍

Google Cloud Datastore 是一种存储大量实时数据的高扩展性和坚固性的无模型文档型数据库,适合于实时应用。Spring Cloud 提供了轻量级应用的快速开发本领,通过美满的插件类层形成一个完备的应用开发组件体系。利用 Spring Cloud 3.x 可以完善场景化地集成 Google Cloud Datastore,轻松实现与 Google Cloud 环境的通信和数据操作。
2.数据库创建

创建数据库

Create a new Cloud Datastore database in your Google Cloud project if this has not already been done to allow Cloud Datastore to create and store entities. https://console.cloud.google.com/datastore/databases

赋予项目中利用的用户访问权限



3. 原理

在 Spring Cloud 中,通过 Spring Data 层提供对 Google Cloud Datastore 的高度封装,利用者可以像操作当地数据一样,优雅场景化地操作 Datastore 中的文档。

  • Spring Data 利用 Google Cloud Datastore 提供的应用端 API。
  • 通过 DatastoreTemplate 调用基础 CRUD 操作方法,并支持自定义查询和处理。
  • 在 Spring Cloud 中,利用配置文件就能实现 Google Cloud Datastore 的快速配置和部署。
4. 代码实现

1. 添加 Maven 依靠

在 pom.xml 文件中添加以下依靠:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <parent>
  6.         <artifactId>spring-cloud-gcp</artifactId>
  7.         <groupId>com.et</groupId>
  8.         <version>1.0-SNAPSHOT</version>
  9.     </parent>
  10.     <modelVersion>4.0.0</modelVersion>
  11.     <artifactId>spring-cloud-gcp-data-datastore-basic-sample</artifactId>
  12.     <properties>
  13.         <maven.compiler.source>17</maven.compiler.source>
  14.         <maven.compiler.target>17</maven.compiler.target>
  15.     </properties>
  16.     <dependencies>
  17.         <dependency>
  18.             <groupId>com.google.cloud</groupId>
  19.             <artifactId>spring-cloud-gcp-starter-data-datastore</artifactId>
  20.         </dependency>
  21.         <dependency>
  22.             <groupId>org.springframework.boot</groupId>
  23.             <artifactId>spring-boot-starter-data-rest</artifactId>
  24.         </dependency>
  25.         <!-- Test-related dependencies. -->
  26.         <dependency>
  27.             <groupId>org.awaitility</groupId>
  28.             <artifactId>awaitility</artifactId>
  29.             <version>4.2.2</version>
  30.             <scope>test</scope>
  31.         </dependency>
  32.         <dependency>
  33.             <groupId>junit</groupId>
  34.             <artifactId>junit</artifactId>
  35.             <scope>test</scope>
  36.         </dependency>
  37.         <dependency>
  38.             <groupId>org.springframework.boot</groupId>
  39.             <artifactId>spring-boot-starter-test</artifactId>
  40.             <scope>test</scope>
  41.         </dependency>
  42.     </dependencies>
  43. </project>
复制代码
2. 配置 Google Cloud 凭资

在 application.properties中配置实现 Datastore 访问:
  1. spring.cloud.gcp.datastore.project-id=feisty-truth-447013-m7
  2. spring.cloud.gcp.datastore.namespace=spring-demo
  3. logging.level.root=WARN
  4. spring.main.allow-circular-references=true
  5. spring.cloud.gcp.credentials.location=file:/home/jxausea/cloudshell_open/feisty-truth-447013-m7-f5b59beab338.json
复制代码
3. 定义文档实例

通过 JPA 类体与 Google Datastore 文档相对应:
  1. /*
  2. * Copyright 2017-2018 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.et;
  17. import com.google.cloud.spring.data.datastore.core.mapping.Entity;
  18. import org.springframework.data.annotation.Id;
  19. /** This class represents a single book stored in Datastore. */
  20. @Entity(name = "books")
  21. public class Book {
  22.   @Id Long id;
  23.   private final String title;
  24.   private final String author;
  25.   private final int year;
  26.   public Book(String title, String author, int year) {
  27.     this.title = title;
  28.     this.author = author;
  29.     this.year = year;
  30.   }
  31.   public long getId() {
  32.     return this.id;
  33.   }
  34.   @Override
  35.   public String toString() {
  36.     return "Book{"
  37.         + "id="
  38.         + this.id
  39.         + ", title='"
  40.         + this.title
  41.         + '\''
  42.         + ", author='"
  43.         + this.author
  44.         + '\''
  45.         + ", year="
  46.         + this.year
  47.         + '}';
  48.   }
  49. }
复制代码
4. 创建数据操作代码

利用 Spring Data Repository 扩展 Datastore CRUD 功能:
  1. /*
  2. * Copyright 2017-2018 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.et;
  17. import com.google.cloud.spring.data.datastore.repository.DatastoreRepository;
  18. import java.util.List;
  19. /**
  20. * This interface contains custom-defined query methods of which implementations are generated for
  21. * you.
  22. */
  23. public interface BookRepository extends DatastoreRepository<Book, Long> {
  24.   List<Book> findByAuthor(String author);
  25.   List<Book> findByYearGreaterThan(int year);
  26.   List<Book> findByAuthorAndYear(String author, int year);
  27. }
复制代码
5. 实现主逻辑

通过利用 Repository 实现主逻辑:
  1. /*
  2. * Copyright 2017-2022 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.et;
  17. import org.springframework.web.bind.annotation.*;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Optional;
  21. @RestController
  22. public class BookController {
  23.   private final BookRepository bookRepository;
  24.   public BookController(BookRepository bookRepository) {
  25.     this.bookRepository = bookRepository;
  26.   }
  27.   @PostMapping("/saveBook")
  28.   public String saveBook(@RequestBody Book book) {
  29.     if (book == null) {
  30.       return "The book is invalid";
  31.     }
  32.     this.bookRepository.save(book);
  33.     return "success";
  34.   }
  35.   @GetMapping("/findAllBooks")
  36.   public String findAllBooks() {
  37.     Iterable<Book> books = this.bookRepository.findAll();
  38.     List<Book> bookList = new ArrayList<>();
  39.     books.forEach(bookList::add);
  40.     return books.toString();
  41.   }
  42.   @GetMapping("/findByAuthor")
  43.   public String findByAuthor(@RequestParam("author") String author) {
  44.     List<Book> books = this.bookRepository.findByAuthor(author);
  45.     return books.toString();
  46.   }
  47.   @GetMapping("/findByYearGreaterThan")
  48.   public String findByYearGreaterThan(@RequestParam("year") Optional<Integer> year) {
  49.     List<Book> books = this.bookRepository.findByYearGreaterThan(year.orElse(0));
  50.     return books.toString();
  51.   }
  52.   @GetMapping("/findByAuthorYear")
  53.   public String findByAuthorYear(
  54.       @RequestParam("author") String author,
  55.       @RequestParam("year") Optional<Integer> year) {
  56.     List<Book> books = this.bookRepository.findByAuthorAndYear(author, year.orElse(0));
  57.     return books.toString();
  58.   }
  59.   @DeleteMapping("/removeAllBooks")
  60.   public void removeAllBooks() {
  61.     this.bookRepository.deleteAll();
  62.   }
  63. }
复制代码
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库



  • GitHub - Harries/springcloud-demo: Spring Cloud tutorial about hystrix,eureka,config,admin,skywalking( Spring  Cloud GCP/spring-cloud-gcp-data-datastore-basic-sample)
5. 测试

1. 启动应用

确保以上配置正确后,启动 Spring Boot 应用,利用 Postman 或 curl 调用程序。(因为网络原因,最好在cloud shell editor启动)

2. 提交请求例子

创建4本书
  1. curl --location --request POST 'localhost:8080/saveBook' \
  2. --header 'Content-Type: application/json' \
  3. --data-raw '{
  4.     "title": "The Moon Is a Harsh Mistress",
  5.     "author": "Robert A. Heinlein",
  6.     "year": 1966
  7. }'
  8. curl --location --request POST 'localhost:8080/saveBook' \
  9. --header 'Content-Type: application/json' \
  10. --data-raw '{
  11.     "title": "Stranger in a Strange Land",
  12.     "author": "Robert A. Heinlein",
  13.     "year": 1961
  14. }'
  15. curl --location --request POST 'localhost:8080/saveBook' \
  16. --header 'Content-Type: application/json' \
  17. --data-raw '{
  18.     "title": "The Crack in Space",
  19.     "author": "Philip K. Dick",
  20.     "year": 1966
  21. }'
  22. curl --location --request POST 'localhost:8080/saveBook' \
  23. --header 'Content-Type: application/json' \
  24. --data-raw '{
  25.     "title": "Ubik",
  26.     "author": "Philip K. Dick",
  27.     "year": 1969
  28. }'
复制代码
查询全部的书
  1. curl --location --request GET 'localhost:8080/findAllBooks'
复制代码
根据作者查询
  1. curl --location --request GET 'localhost:8080/findByAuthor?author=Robert A. Heinlein'
复制代码
根据日期筛选
  1. curl --location --request GET 'localhost:8080/findByYearGreaterThan?year=1960'
复制代码
根据作者和日期筛选
  1. curl --location --request GET 'localhost:8080/findByAuthorYear?author=Robert A. Heinlein&year=1966'
复制代码
删除
  1. curl --location --request DELETE 'localhost:8080/removeAllBooks'
复制代码
6. 总结

通过上述步调,我们完成了 Spring Cloud 3.x 集成 Google Datastore 的基础实现。这不仅仅是一个实现,还提供了一种解决方案,可以轻松处理任务的数据存储和查询需求。
7.引用



  • spring-cloud-gcp/spring-cloud-gcp-samples/spring-cloud-gcp-data-datastore-basic-sample at main · GoogleCloudPlatform/spring-cloud-gcp · GitHub
  • Spring Cloud 3.x 集成 Google Datastore快速入门DEMO | Harries Blog™

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

宁睿

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表