Spring Cloud – Bootstrapping – Spring Cloud – Bootstrapping

最后修改: 2016年 9月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Spring Cloud is a framework for building robust cloud applications. The framework facilitates the development of applications by providing solutions to many of the common problems faced when moving to a distributed environment.

Spring Cloud是一个用于构建强大的云应用程序的框架。该框架通过为转移到分布式环境时面临的许多常见问题提供解决方案,促进了应用程序的开发。

Applications that run with microservices architecture aim to simplify development, deployment, and maintenance. The decomposed nature of the application allows developers to focus on one problem at a time. Improvements can be introduced without impacting other parts of a system.

采用微服务架构运行的应用程序旨在简化开发、部署和维护。应用程序的分解性质使开发人员能够一次专注于一个问题。可以在不影响系统的其他部分的情况下引入改进措施。

On the other hand, different challenges arise when we take on a microservice approach:

另一方面,当我们采取微服务的方式时,会出现不同的挑战。

  • Externalizing configuration so that is flexible and does not require rebuild of the service on change
  • Service discovery
  • Hiding complexity of services deployed on different hosts

In this article, we’ll build five microservices: a configuration server, a discovery server, a gateway server, a book service, and finally a rating service. These five microservices form a solid base application to begin cloud development and address the aforementioned challenges.

在这篇文章中,我们将构建五个微服务:一个配置服务器、一个发现服务器、一个网关服务器、一个图书服务和最后一个评级服务。这五个微服务构成了一个坚实的基础应用,可以开始云计算开发并解决上述挑战。

2. Config Server

2.配置服务器

When developing a cloud application, one issue is maintaining and distributing configuration to our services. We really don’t want to spend time configuring each environment before scaling our service horizontally or risk security breaches by baking our configuration into our application.

在开发云计算应用时,有一个问题是维护和分配配置给我们的服务。我们真的不想在横向扩展我们的服务之前花时间配置每个环境,或者冒着安全漏洞的风险把我们的配置烘烤到我们的应用程序。

To solve this, we will consolidate all of our configuration into a single Git repository and connect that to one application that manages a configuration for all our applications. We are going to be setting up a very simple implementation.

为了解决这个问题,我们将把所有的配置整合到一个Git仓库中,并把它连接到一个管理所有应用程序配置的应用程序上。我们将建立一个非常简单的实现。

To learn more details and see a more complex example, take a look at our Spring Cloud Configuration article.

要了解更多细节并查看更复杂的示例,请看我们的Spring Cloud Configuration文章。

2.1. Setup

2.1.设置

Navigate to https://start.spring.io and select Maven and Spring Boot 2.2.x.

导航到 https://start.spring.io,选择Maven和Spring Boot 2.2.x。

Set the artifact to “config. In the dependencies section, search for “config server” and add that module. Then press the generate button and we’ll be able to download a zip file with a preconfigured project inside and ready to go.

将工件设置为 “config。在依赖性部分,搜索 “config server “并添加该模块。然后按下generate按钮,我们就可以下载一个压缩文件,里面有一个预先配置好的项目,可以开始使用。

Alternatively, we can generate a Spring Boot project and add some dependencies to the POM file manually.

另外,我们可以生成一个Spring Boot项目,并手动添加一些依赖关系到POM文件中。

These dependencies will be shared between all the projects:

这些依赖关系将在所有项目之间共享。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies> 

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Let’s add a dependency for the config server:

让我们为配置服务器添加一个依赖项。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

For reference, we can find the latest version on Maven Central (spring-cloud-dependencies, test, config-server).

作为参考,我们可以在Maven中心找到最新版本(spring-cloud-dependencies, test, config-server)。

2.2. Spring Config

2.2.Spring配置

To enable the configuration server we must add some annotations to the main application class:

为了启用配置服务器,我们必须向主应用程序类添加一些注释。

@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {...}

@EnableConfigServer will turn our application into a configuration server.

@EnableConfigServer将把我们的应用程序变成一个配置服务器。

2.3. Properties

2.3.属性

Let’s add the application.properties in src/main/resources:

让我们在src/main/resources中添加application.properties

server.port=8081
spring.application.name=config

spring.cloud.config.server.git.uri=file://${user.home}/application-config

The most significant setting for the config server is the git.uri parameter. This is currently set to a relative file path that generally resolves to c:\Users\{username}\ on Windows or /Users/{username}/ on *nix. This property points to a Git repository where the property files for all the other applications are stored. It can be set to an absolute file path if necessary.

对配置服务器最重要的设置是git.uri参数。目前这个参数被设置为一个相对的文件路径,在Windows下一般解析为c:\Users\{username},在*nix下为/Users/{username}/。这个属性指向一个Git仓库,所有其他应用程序的属性文件都存储在那里。如果需要,它可以被设置为一个绝对的文件路径。

Tip: On a windows machine preface the value with “file:///”, on *nix then use “file://”.

提示。在WINDOWS机器上用 “file:///”作前缀,在*NIX上则用 “file://”。

2.4. Git Repository

2.4.Git存储库

Navigate to the folder defined by spring.cloud.config.server.git.uri and add the folder application-config. CD into that folder and type git init. This will initialize a Git repository where we can store files and track their changes.

导航到spring.cloud.config.server.git.uri定义的文件夹,并添加文件夹application-config。CD进入该文件夹并输入git init。这将初始化一个Git仓库,我们可以在那里存储文件并跟踪其变化。

2.5. Run

2.5.运行

Let’s run config server and make sure it is working. From the command line type mvn spring-boot:run. This will start the server.

让我们运行配置服务器并确保其工作。在命令行中输入mvn spring-boot:run。这将启动服务器。

We should see this output indicating the server is running:

我们应该看到这个输出,表明服务器正在运行。

Tomcat started on port(s): 8081 (http)

2.6. Bootstrapping Configuration

2.6.引导配置

In our subsequent servers, we’re going to want their application properties managed by this config server. To do that, we’ll actually need to do a bit of chicken-and-egg: Configure properties in each application that know how to talk back to this server.

在我们后续的服务器中,我们将希望他们的应用程序属性由这个配置服务器管理。要做到这一点,我们实际上需要做一点鸡生蛋蛋生鸡的事情:在每个应用程序中配置知道如何与该服务器对话的属性。

It’s a bootstrap process, and each one of these apps is going to have a file called bootstrap.properties. It will contain properties just like application.properties but with a twist:

这是一个引导过程,每个应用程序都将有一个名为bootstrap.properties的文件。它将包含与application.properties一样的属性,但有一个变化。

A parent Spring ApplicationContext loads the bootstrap.properties first. This is critical so that Config Server can start managing the properties in application.properties. It’s this special ApplicationContext that will also decrypt any encrypted application properties.

父Spring ApplicationContext 首先加载bootstrap.properties 这一点至关重要,以便Config Server能够开始管理application.properties中的属性。正是这个特殊的ApplicationContext,也将解密任何加密的应用程序属性。

It’s smart to keep these properties files distinct. bootstrap.properties is for getting the config server ready, and application.properties is for properties specific to our application. Technically, though, it’s possible to place application properties in bootstrap.properties.

保持这些属性文件的不同是明智的。 bootstrap.properties是为了让配置服务器准备好,而application.properties是为了我们应用程序的特定属性。但从技术上讲,我们可以将应用属性放在bootstrap.properties中。

Lastly, since Config Server is managing our application properties, one might wonder why have an application.properties at all? The answer is that these still come in handy as default values that perhaps Config Server doesn’t have.

最后,由于配置服务器正在管理我们的应用程序属性,人们可能会问为什么要有一个application.properties?答案是,这些东西作为默认值还是很有用的,也许Config Server并没有。

3. Discovery

3.发现

Now that we have configuration taken care of, we need a way for all of our servers to be able to find each other. We will solve this problem by setting the Eureka discovery server up. Since our applications could be running on any ip/port combination we need a central address registry that can serve as an application address lookup.

现在我们已经解决了配置问题,我们需要一种方法让我们所有的服务器能够找到彼此。我们将通过设置Eureka发现服务器来解决这个问题。由于我们的应用程序可以在任何IP/端口组合上运行,我们需要一个中央地址注册表,它可以作为应用程序地址查询。

When a new server is provisioned it will communicate with the discovery server and register its address so that others can communicate with it. This way other applications can consume this information as they make requests.

当一个新的服务器被提供时,它将与发现服务器通信,并注册其地址,以便其他人可以与它通信。这样,其他应用程序在发出请求时就可以消费这些信息。

To learn more details and see a more complex discovery implementation take a look at Spring Cloud Eureka article.

要了解更多细节并看到更复杂的发现实施,请看Spring Cloud Eureka文章

3.1. Setup

3.1.设置

Again we’ll navigate to start.spring.io. Set the artifact to “discovery”. Search for “eureka server” and add that dependency. Search for “config client” and add that dependency. Finally, generate the project.

我们将再次导航到start.spring.io。将工件设置为 “发现”。搜索 “eureka server “并添加该依赖项。搜索 “config client “并添加该依赖项。最后,生成该项目。

Alternatively, we can create a Spring Boot project, copy the contents of the POM from config server and swap in these dependencies:

另外,我们可以创建一个Spring Boot项目,从配置服务器上复制POM的内容,并换入这些依赖项。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

For reference, we’ll find the bundles on Maven Central (config-client, eureka-server).

作为参考,我们将在Maven中心找到这些捆绑包(config-client, eureka-server)。

3.2. Spring Config

3.2.Spring配置

Let’s add Java config to the main class:

让我们在主类中加入Java配置。

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {...}

@EnableEurekaServer will configure this server as a discovery server using Netflix Eureka. Spring Boot will automatically detect the configuration dependency on the classpath and lookup the configuration from the config server.

@EnableEurekaServer将使用Netflix Eureka将该服务器配置为发现服务器。Spring Boot将自动检测classpath上的配置依赖性,并从配置服务器上查找该配置。

3.3. Properties

3.3.属性

Now we will add two properties files:

现在我们将添加两个属性文件。

First, we add bootstrap.properties into src/main/resources:

首先,我们将bootstrap.properties添加到src/main/resources

spring.cloud.config.name=discovery
spring.cloud.config.uri=http://localhost:8081

These properties will let discovery server query the config server at startup.

这些属性将让发现服务器在启动时查询配置服务器。

And second, we add discovery.properties to our Git repository

其次,我们将discovery.properties添加到我们的Git存储库中

spring.application.name=discovery
server.port=8082

eureka.instance.hostname=localhost

eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

The filename must match the spring.application.name property.

文件名必须符合spring.application.name属性。

In addition, we are telling this server that it is operating in the default zone, this matches the config client’s region setting. We are also telling the server not to register with another discovery instance.

此外,我们告诉这个服务器,它是在默认区域内运行的,这与配置客户端的区域设置相匹配。我们还告诉该服务器不要向另一个发现实例注册。

In production, we’d have more than one of these to provide redundancy in the event of failure and that setting would be true.

在生产中,我们会有不止一个这样的设备,以便在发生故障时提供冗余,这种设置是真实的。

Let’s commit the file to the Git repository. Otherwise, the file will not be detected.

让我们把文件提交到 Git 仓库。否则,该文件将不会被检测到。

3.4. Add Dependency to the Config Server

3.4.向配置服务器添加依赖关系

Add this dependency to the config server POM file:

把这个依赖关系添加到配置服务器的POM文件中。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

For reference, we can find the bundle on Maven Central (eureka-client).

作为参考,我们可以在Maven中心(eureka-client)找到该捆绑包。

Add these properties to the application.properties file in src/main/resources of the config server:

将这些属性添加到配置服务器的src/main/resources中的application.properties文件。

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

3.5. Run

3.5 运行

Start the discovery server using the same command, mvn spring-boot:run. The output from the command line should include:

使用相同的命令启动发现服务器,mvn spring-boot:run。命令行的输出应该包括。

Fetching config from server at: http://localhost:8081
...
Tomcat started on port(s): 8082 (http)

Stop and rerun the config service. If all is good output should look like:

停止并重新运行配置服务。如果一切正常,输出应该是这样的。

DiscoveryClient_CONFIG/10.1.10.235:config:8081: registering service...
Tomcat started on port(s): 8081 (http)
DiscoveryClient_CONFIG/10.1.10.235:config:8081 - registration status: 204

4. Gateway

4.网关

Now that we have our configuration and discovery issues resolved we still have a problem with clients accessing all of our applications.

现在我们已经解决了配置和发现问题,但我们仍然有一个问题,即客户访问我们所有的应用程序。

If we leave everything in a distributed system, then we will have to manage complex CORS headers to allow cross-origin requests on clients. We can resolve this by creating a gateway server. This will act as a reverse proxy shuttling requests from clients to our back end servers.

如果我们把一切都留在分布式系统中,那么我们将不得不管理复杂的 CORS 头信息,以允许客户端的跨源请求。我们可以通过创建一个网关服务器来解决这个问题。这将充当一个反向代理,把客户的请求穿梭到我们的后端服务器。

A gateway server is an excellent application in microservice architecture as it allows all responses to originate from a single host. This will eliminate the need for CORS and give us a convenient place to handle common problems like authentication.

网关服务器在微服务架构中是一个很好的应用,因为它允许所有的响应都来自一个单一的主机。这将消除对CORS的需求,并给我们一个方便的地方来处理诸如认证等常见问题。

4.1. Setup

4.1.设置

By now we know the drill. Navigate to https://start.spring.io. Set the artifact to “gateway”. Search for “zuul” and add that dependency. Search for “config client” and add that dependency. Search for “eureka discovery” and add that dependency. Lastly, generate that project.

现在我们已经知道了演习的内容。导航到https://start.spring.io。将工件设置为 “gateway”。搜索 “zuul “并添加该依赖项。搜索 “config client “并添加该依赖关系。搜索 “eureka discovery “并添加该依赖关系。最后,生成该项目。

Alternatively, we could create a Spring Boot app with these dependencies:

另外,我们可以用这些依赖项创建一个Spring Boot应用程序。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

For reference, we can find the bundle on Maven Central (config-client, eureka-client, zuul).

作为参考,我们可以在Maven中心找到该软件包(config-client, eureka-client, zuul)。

4.2. Spring Config

4.2.Spring配置

Let’s add the configuration to the main class:

让我们把配置添加到主类中。

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableFeignClients
public class GatewayApplication {...}

4.3. Properties

4.3.属性

Now we will add two properties files:

现在我们将添加两个属性文件。

bootstrap.properties in src/main/resources:

bootstrap.propertiessrc/main/resources

spring.cloud.config.name=gateway
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true

eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

gateway.properties in our Git repository

gateway.properties在我们的Git存储库中。

spring.application.name=gateway
server.port=8080

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5

zuul.routes.book-service.path=/book-service/**
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000

zuul.routes.rating-service.path=/rating-service/**
zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000

zuul.routes.discovery.path=/discovery/**
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
zuul.routes.discovery.url=http://localhost:8082
hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000

The zuul.routes property allows us to define an application to route certain requests based on an ant URL matcher. Our property tells Zuul to route any request that comes in on /book-service/** to an application with the spring.application.name of book-service. Zuul will then lookup the host from discovery server using the application name and forward the request to that server.

zuul.routes属性允许我们定义一个应用程序,根据ant URL匹配器路由某些请求。我们的属性告诉Zuul将任何来自/book-service/**的请求路由到spring.application.namebook-service应用程序。然后Zuul将使用应用程序名称从发现服务器上查找主机,并将请求转发到该服务器。

Remember to commit the changes in the repository!

记住要在版本库中提交修改!

4.4. Run

4.4.运行

Run the config and discovery applications and wait until the config application has registered with the discovery server. If they are already running, we don’t have to restart them. Once that is complete, run the gateway server. The gateway server should start on port 8080 and register itself with the discovery server. The output from the console should contain:

运行配置和发现程序,等待配置程序在发现服务器上注册。如果它们已经在运行,我们不必重新启动它们。一旦完成,运行网关服务器。网关服务器应该在8080端口启动,并在发现服务器上注册自己。控制台的输出应该包含。

Fetching config from server at: http://10.1.10.235:8081/
...
DiscoveryClient_GATEWAY/10.1.10.235:gateway:8080: registering service...
DiscoveryClient_GATEWAY/10.1.10.235:gateway:8080 - registration status: 204
Tomcat started on port(s): 8080 (http)

One mistake that is easy to make is to start the server before config server has registered with Eureka. In this case, we’ll see a log with this output:

一个容易犯的错误是在配置服务器在Eureka上注册之前就启动服务器。在这种情况下,我们会看到一个有这样输出的日志。

Fetching config from server at: http://localhost:8888

This is the default URL and port for a config server and indicates our discovery service did not have an address when the configuration request was made. Just wait a few seconds and try again, once the config server has registered with Eureka, the problem will resolve.

这是配置服务器的默认URL和端口,表明我们的发现服务在发出配置请求时没有一个地址。只要等几秒钟再试,一旦配置服务器在尤里卡注册,问题就会解决。

5. Book Service

5.预订服务

In microservice architecture, we are free to make as many applications to meet a business objective. Often engineers will divide their services by domain. We will follow this pattern and create a book service to handle all the operations for books in our application.

在微服务架构中,我们可以自由地制作尽可能多的应用程序来满足业务目标。通常情况下,工程师会按领域划分他们的服务。我们将遵循这种模式,创建一个图书服务来处理我们应用程序中所有的图书操作。

5.1. Setup

5.1.设置

One more time. Navigate to https://start.spring.io. Set the artifact to “book-service”. Search for “web” and add that dependency. Search for “config client” and add that dependency. Search for “eureka discovery” and add that dependency. Generate that project.

再来一次。导航到https://start.spring.io。将工件设置为 “book-service”。搜索 “web “并添加该依赖项。搜索 “config client “并添加该依赖关系。搜索 “eureka discovery “并添加该依赖关系。生成该项目。

Alternatively, add these dependencies to a project:

或者,将这些依赖关系添加到一个项目中。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

For reference, we can find the bundle on Maven Central (config-client, eureka-client, web).

作为参考,我们可以在Maven中心找到该软件包(config-client, eureka-client, web)。

5.2. Spring Config

5.2.Spring配置

Let’s modify our main class:

让我们来修改我们的主类。

@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/books")
public class BookServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookServiceApplication.class, args);
    }

    private List<Book> bookList = Arrays.asList(
        new Book(1L, "Baeldung goes to the market", "Tim Schimandle"),
        new Book(2L, "Baeldung goes to the park", "Slavisa")
    );

    @GetMapping("")
    public List<Book> findAllBooks() {
        return bookList;
    }

    @GetMapping("/{bookId}")
    public Book findBook(@PathVariable Long bookId) {
        return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null);
    }
}

We also added a REST controller and a field set by our properties file to return a value we will set during configuration.

我们还添加了一个REST控制器和一个由我们的属性文件设置的字段,以返回一个我们将在配置过程中设置的值。

Let’s now add the book POJO:

现在让我们添加书中的POJO。

public class Book {
    private Long id;
    private String author;
    private String title;

    // standard getters and setters
}

5.3. Properties

5.3.属性

Now we just need to add our two properties files:

现在我们只需要添加我们的两个属性文件。

bootstrap.properties in src/main/resources:

bootstrap.propertiessrc/main/resources

spring.cloud.config.name=book-service
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true

eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

book-service.properties in our Git repository:

book-service.properties在我们的Git存储库中。

spring.application.name=book-service
server.port=8083

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

Let’s commit the changes to the repository.

让我们把修改提交到版本库。

5.4. Run

5.4.运行

Once all the other applications have started we can start the book service. The console output should look like:

一旦所有其他应用程序都启动了,我们就可以启动图书服务。控制台的输出应该是这样的。

DiscoveryClient_BOOK-SERVICE/10.1.10.235:book-service:8083: registering service...
DiscoveryClient_BOOK-SERVICE/10.1.10.235:book-service:8083 - registration status: 204
Tomcat started on port(s): 8083 (http)

Once it is up we can use our browser to access the endpoint we just created. Navigate to http://localhost:8080/book-service/books and we get back a JSON object with two books we added in out controller. Notice that we are not accessing book service directly on port 8083 but we are going through the gateway server.

一旦它建立起来,我们就可以用浏览器访问我们刚刚创建的端点。导航到http://localhost:8080/book-service/books,我们会得到一个JSON对象,里面有我们在控制器中添加的两本书。注意,我们不是直接访问8083端口的图书服务,而是通过网关服务器。

6. Rating Service

6.评级服务

Like our book service, our rating service will be a domain driven service that will handle operations related to ratings.

像我们的图书服务一样,我们的评级服务将是一个领域驱动的服务,将处理与评级有关的操作。

6.1. Setup

6.1.设置

One more time. Navigate to https://start.spring.io. Set the artifact to “rating-service”. Search for “web” and add that dependency. Search for “config client” and add that dependency. Search for eureka discovery and add that dependency. Then, generate that project.

再来一次。导航到https://start.spring.io。将工件设置为 “评级服务”。搜索 “web “并添加该依赖关系。搜索 “config client “并添加该依赖关系。搜索eureka discovery并添加该依赖项。然后,生成该项目。

Alternatively, add these dependencies to a project:

或者,将这些依赖关系添加到一个项目中。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

For reference, we can find the bundle on Maven Central (config-client, eureka-client, web).

作为参考,我们可以在Maven中心找到该软件包(config-client, eureka-client, web)。

6.2. Spring Config

6.2.Spring配置

Let’s modify our main class:

让我们来修改我们的主类。

@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/ratings")
public class RatingServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(RatingServiceApplication.class, args);
    }

    private List<Rating> ratingList = Arrays.asList(
        new Rating(1L, 1L, 2),
        new Rating(2L, 1L, 3),
        new Rating(3L, 2L, 4),
        new Rating(4L, 2L, 5)
    );

    @GetMapping("")
    public List<Rating> findRatingsByBookId(@RequestParam Long bookId) {
        return bookId == null || bookId.equals(0L) ? Collections.EMPTY_LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList());
    }

    @GetMapping("/all")
    public List<Rating> findAllRatings() {
        return ratingList;
    }
}

We also added a REST controller and a field set by our properties file to return a value we will set during configuration.

我们还添加了一个REST控制器和一个由我们的属性文件设置的字段,以返回一个我们将在配置过程中设置的值。

Let’s add the rating POJO:

让我们添加评级POJO。

public class Rating {
    private Long id;
    private Long bookId;
    private int stars;

    //standard getters and setters
}

6.3. Properties

6.3.属性

Now we just need to add our two properties files:

现在我们只需要添加我们的两个属性文件。

bootstrap.properties in src/main/resources:

bootstrap.propertiessrc/main/resources

spring.cloud.config.name=rating-service
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true

eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

rating-service.properties in our Git repository:

rating-service.properties在我们的Git存储库中。

spring.application.name=rating-service
server.port=8084

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

Let’s commit the changes to the repository.

让我们把修改提交到版本库。

6.4. Run

6.4.运行

Once all the other applications have started we can start the rating service. The console output should look like:

一旦所有其他应用程序都启动了,我们就可以启动评级服务。控制台的输出应该是这样的。

DiscoveryClient_RATING-SERVICE/10.1.10.235:rating-service:8083: registering service...
DiscoveryClient_RATING-SERVICE/10.1.10.235:rating-service:8083 - registration status: 204
Tomcat started on port(s): 8084 (http)

Once it is up we can use our browser to access the endpoint we just created. Navigate to http://localhost:8080/rating-service/ratings/all and we get back JSON containing all our ratings. Notice that we are not accessing the rating service directly on port 8084 but we are going through the gateway server.

一旦它建立起来,我们就可以使用我们的浏览器来访问我们刚刚创建的端点。导航到http://localhost:8080/rating-service/ratings/all,我们会得到包含我们所有评级的JSON。注意,我们不是直接访问8084端口的评级服务,而是通过网关服务器。

7. Conclusion

7.结论

Now we are able to connect the various pieces of Spring Cloud into a functioning microservice application. This forms a base we can use to begin building more complex applications.

现在我们能够将Spring Cloud的各个部分连接成一个有效的微服务应用程序。这形成了一个基础,我们可以用来开始建立更复杂的应用程序。

As always, we can find this source code over on GitHub.

一如既往,我们可以在GitHub上找到这个源代码。