Spring Cloud overview

Starting with this article, we’ll officially embark on a journey to explore the secrets of Spring Cloud. By the end of this article, the reader will have learned to build a complete distributed architecture to move closer to the architect’s goals.

Introduction to the

Spring Cloud, based on Spring Boot, is a concrete implementation of the micro-service architecture idea. It provides developers with some tools to quickly build common patterns in distributed systems, such as configuration management, service discovery, fuses, intelligent routing, micro-agent, control bus, etc. The underlying Spring Cloud is based on the Spring Boot framework, which does not repeatedly “build the wheel”, but integrates some third-party implementations of microservices application modules.

Spring Cloud is an ordered collection of frameworks, and here are some of the subprojects we might use in real projects.

  • Spring Cloud Config: Centralized storage of configurations through repositories such as SVN and Git. Configuration resources can be directly mapped to the Spring Environment.
  • Spring Cloud Netflix: Integrates with various components developed by Netflix, including service registration and discovery, fuses, service gateways, Rest clients, and load balancers.
  • Spring Cloud Bus: An event Bus linking services, service instances, and distributed messages; Used to propagate state changes in the cluster; In conjunction with Spring Cloud Config, dynamic refreshing of configuration is possible.
  • Spring Cloud Consul: Performs service registration and discovery configuration management in Spring Cloud.
  • Spring Cloud Security: Provides support for load-balancing OAuth2REST clients and authentication relaying in Zuul agents.
  • Spring Cloud Sleuth: Distributed tracing for Spring Cloud applications, compatible with Zipkin, HTrace, and log-based (for example, ELK) tracing.
  • Spring Cloud Data Flow: A cloud-native choreography service that can be used in modern runtimes and can compose microservice applications. Easy-to-use DSLS, drag-and-drop GUIs, and REST-apis work together to simplify the overall choreography of microservices-based data pipelines.
  • Spring Cloud Stream: Lightweight event-driven microservices framework for quickly building applications that can connect to external systems for sending and receiving messages between Spring Boot applications using Apache Kafka or RabbitMQ.
  • Spring Cloud Task: A transient microservice framework for quickly building applications that perform limited data processing, which is used to add simple declarations of functionality and non-functionality to Spring Boot applications.
  • Spring Cloud Gateway: An intelligent programmable router based on Project Reactor. Due to delays in Zuul 2.0 development, Spring has officially developed a routing gateway to support Spring Boot 2.0 and the new Spring Cloud.
  • Spring Cloud OpenFeign: Based on Netflix Feign, Spring Cloud OpenFeign is a declarative HTTP client that can easily implement indirect service calls.
  • Spring Cloud Function: Facilitates the implementation of business logic through functions that support a unified programming model across serverless vendors and run independently (local or PaaS).

These projects are not all concentrated on one application. The purpose of listing them is to facilitate the readers to select some suitable components to integrate into the application when building the micro-server architecture based on SpringCloud.

The advantages and disadvantages

At a time when technology is changing so frequently, surviving frameworks have their merits. So what are the advantages of Spring Cloud? Let’s talk about it.

  • Integrator: Covers all aspects of the microservices architecture. Convention over configuration: Based on annotations, no configuration files.
  • Lightweight Components: The integrated components are mostly lightweight and are the best in their field.
  • Ease of development: There is a lot of packaging for components, which simplifies development.
  • Flexible development: Components are decoupled, giving developers the flexibility to choose components on demand.

Everything has two sides, and Spring Cloud is no exception. It mainly has the following disadvantages.

  • The project structure is complex: each component or service needs to create a project.
  • High deployment threshold: Cluster deployment requires collaboration with container technologies such as Docker. However, it costs a lot to learn Docker in depth.

The advantages of Spring Cloud are obvious, so it is a good choice for readers who want to study microservices architecture.

The status quo

Currently, there are not many companies using Spring Cloud as their main technology stack in China. This is not because Spring Cloud is bad, but for several reasons.

  • There are few Chinese documents in Spring Cloud, so there are not many solutions for problems.
  • Many of the tech leaders of Chinese startups used to work at Alibaba, and they use Dubbo to build microservices.
  • Large companies generally have their own distributed solutions, while small and medium-sized companies have architectures that do not use microservices, so there is no need to adopt Spring Cloud.

But microservices architecture is a trend, and Spring Cloud is the leader in microservices solutions, which is why I wrote this book.

Start Spring Cloud practice

Learning any language or framework is started by Hello World, and this book is no exception. Before we get into the game, let’s set up a simple Spring Cloud framework so you can appreciate its power.

Technical reserves

Before starting Spring Cloud, readers should have the following technical reserves.

Java Basics: If your Java basics are not solid enough, you are advised to read this article first.

Spring MVC: Spring Cloud is based on Spring Boot, and Spring Boot is based on Spring MVC, so readers need to have a foundation in the Spring MVC framework.

The preparatory work

This article uses IntelliJIDEA to develop the Spring Cloud project. If you have not installed the tool, you can download the latest version from www.jetbrains.com/idea/. …

The Spring Boot version used in this article is 2.0.3.RELEASE and the Spring Cloud version is finchley.release, so JDK version is at least 1.8 or older. In addition, the book contains a large number of lambda expressions, and readers need to know lambda expressions as well, otherwise some code may be unreadable.

Start your field trip with Hello World

Let’s start building a simple Spring Cloud framework that includes registration and discovery of services, clients, and service gateways. Spring Cloud is a microservice architecture that contains multiple projects, so we should first create a parent project and set it to poM, with each child project created under the parent project.

Open IntelliJ IDEA, create a Maven project, name it SpringCloudDemo, and modify the contents of POM.xml:

<packaging>pom</packaging><parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</ ArtifactId > < version > 2.0.3. RELEASE < / version > < relativePath / > < / parent > < properties > <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < Java version > 1.8 < / Java version > < / properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId></ dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId><version>Finchley.RELEASE</version> <type>pom</type> <scope>import< / scope></dependency> </ dependencies> </dependencyManagement>Copy the code

XML requires a dependency on the Hystrix fuse. This is because Spring Cloud adds this dependency by default. If you do not add this dependency, the startup project will report an error.

Once the parent project is created, you can create the child project and implement the simplest Spring Cloud project.

1. Registration and discovery of services

Spring Cloud’s default service registration and discovery component is Netflix’s Eureka component, which is described in more detail in Chapter 6. This section also uses its default component to create service registration and discovery.

Spring Cloud integrates Eureka into the microservices family and rewraps it. Eureka is responsible for the service governance functions in the microservices architecture. Service governance is the core idea of microservices architecture, which can realize the registration, discovery, destruction and renewal of services.

(1) Right-click the SpringCloudDemo project and choose New→Module from the pop-up shortcut menu (as shown in Figure 4-2). In the New Module window that opens, name the ArtifactIld eurekaserver, as shown in Figure 4-3, and keep clicking the Next button.

(2) Add the following dependencies to pom. XML:

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>
</dependencies>
Copy the code

Eureka components are divided into a server and a client. The server is responsible for managing the client, such as registration, destruction, and renewal. After adding the above dependencies, we can set up the project as the Eureka server to manage the Eureka client.

Create class Application:

@EnableEurekaServer @SpringCloudApplicationpublic class Application { public static void main(String[] args){ SpringApplication.run(Application.class, args); }}Copy the code

Application is the startup class for the project. As we know, the entry function of a Java program is the main method. In the code above, we add the main method to the Application class and start a Spring Cloud project by calling the Run method through the SpringApplication.

In addition, we added @Enableeurekaserver and @SpringCloudApplication annotations to the Application class. The first annotation indicates that the current project is set up as a registry. Only by adding this annotation can the current project act as a server for registration and discovery, which indicates that the project is a Spring Cloud project.

The source of the @SpringCloudApplication annotation is as follows:

@Target({ElementType. TYPE})
@Retention(RetentionPolicy.RUNTIME)@Documented
@Inherited
@SpringBootApplication@EnableDiscoveryclient@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
Copy the code

As you can see, it also contains three core annotations :@SpringBootApplication, @EnableDiscoveryClient, and @Enablecircuitbreaker. As discussed in Chapter 2, the @springBootApplication annotation must be added to the bootclass of a SpringBoot project, otherwise the project will not start properly. @enableDiscoveryClient Indicates that the project can be registered in the registry as a client. @enablecircuitbreaker Indicates that a fuse is turned on. See Part 10 for details about fuses.

Create application. Yml under Resources and add the following content:

server:
port: 8761spring:
application :
name: eurekaserver
eureka:
client:
register-with-eureka: truefetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code

The above configuration is the most basic configuration for the registry. Where, spring.application. name defines the application name of the current project. The Eureka server will register with this name, which is replaced with uppercase letters by default. Register-with-eureka Indicates whether the current project is registered with the Eureka server. The default value is true. The eureka client. Fetch -registry can indicate whether the project should obtain the Eureka registry information from the Eureka server. The default value is true, which is mainly used in scenarios such as high availability registry or load balancing. Do not synchronize information from other Eureka servers, so set this parameter to false. Eureka. Client. service-URL indicates the registry to which the project is registered. Eureka is a fixed value and 8761 is the registry port.

Now that service registration and discovery is created, let’s test it. (1) Start the main method of Application class.

(2) Access localhost:8761 in the browser, and you can see the interface as shown in Figure 4-4. The Eureka server will register itself, and the eurekaserver is the application name defined in spring.application.name, which the Eureka server converts to uppercase letters eurekaserver.

2. The client

After the Eureka server is built, we continue to build the client.

Create Module, name it eurekaclient, add dependency to pom.xml:

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></ dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId></ dependency>
</ dependencies>
Copy the code

Spring-cloud-starter-netflix-eureka-client is a dependency of The Eureka client. Only after the dependency is added, the client can be registered with the Eureka server. Spring-boot-starter-web integrates with the Spring MVC framework. This dependency must be added to the Eureka client otherwise the project cannot be started. Figure 4-5 shows the project startup logs.

Figure 4-5 shows that the project automatically stops after it is started. With the spring-boot-starter-web dependency, we can start the project correctly, as shown in Figure 4-6.

(2) Create the startup class Application with the same code as “Register and discover services” in the previous section. Note that this startup class only needs to add @SpringCloudApplication and does not need to add the @Enableeurekaserver annotation.

(3) Create the configuration file application.yml, which has the same code as “Service registration and discovery” in the previous section. Just set server.port to 8762 and Spring.application. name to Eurekaclient.

So let’s test that out.

(1) Start Eurekaserver and Eurekaclient respectively.

(2) Through the browser to visit localhost:8761, we found that Eureka client (EUREKACLIENT) has also been registered, as shown in Figure 4-7.

3. Service gateway

In the Spring Boot 1.x era, the default gateway for Spring Cloud was Netflix’s Zuul 1.0. Zuul 2.0 was also in continuous development, but the development process was bumpy and often delayed. Therefore, Spring Cloud officials did not have the patience to wait, and developed a set of by the Gateway framework. After Spring Boot 2.0, the service Gateway has a new framework, that is, Spring Cloud Gateway.

Zuul 1.0 is a blocking gateway and does not support Websockets. Zuul 2.0 is a non-blocking gateway and supports Websockets. There is no need to integrate Zuul 2.0 since Spring Cloud has officially developed its own gateway with a non-blocking API that supports Websockets, fuses, traffic limiting, and route filtering. Currently, if you continue to rely on Zuul, it is still Zuul 1.0. Zuul 1.0 is significantly less capable of handling concurrency than Spring Cloud Gateway, so this book uses Spring Cloud Gateway as a service Gateway.

Let’s set up the service gateway.

(1) Create a Module under SpringCloudDemo, name it gateway, and add the following dependencies:

<dependencies>
<dependency>
<groupId>org-springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId></dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</ artifactId></dependency>
<dependency>
<groupId>org.springframework.cloud</ groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
</ dependencies>
Copy the code

In the code above, we added the Spring-cloud-starter-gateway dependency so that the project could be set up as a service gateway. The service gateway also needs to register with the Eureka server. Otherwise, it cannot represent other Eureka clients and loses its function as a gateway. Therefore, the spring-cloud-starter-Netflix-Eureka-client dependency needs to be added.

Because The Spring Cloud Gateway uses WebFlux, we need to add a WebFlux dependency. Do not add the spring-boot-starter-web dependency. Otherwise, an error message is displayed, as shown in Figure 4-8.

If we want to implement dynamic routing, we need to register the Spring Cloud Gateway with the registry, at which point we need to add a dependency on the Eureka client.

Create a configuration file application.yml:

server:
port:8080spring:
application:
name: gatewaycloud:
gateway:
discovery:
locator:
enabled: true
eureka:
client:
register-with-eureka: truefetch-registry: true
service-url :
defaultzone: http:// localhost:8761/eureka/
Copy the code

In the above configuration, eureka.client.fetch-registry is set to true, because the external access accesses the specific Eureka client through the service gateway. The service gateway needs to pull the Eureka registry information, otherwise the specific client cannot be discovered. And spring. Cloud. Gateway. Discovery. A locator) enabled for the dynamic routing configuration Settings are open, if it is set to true, said they would through the registry serviceId gateway to request the client interface, The address is HTTP :/localhost:gateway port/serviceId/**. Note That the serviceId registered through the Eureka server is in uppercase, as shown in Figure 4-9.

Therefore, the serviceId for the request address should also be capitalized because it is case sensitive, and serviceId is the spring.application.name we set in application.yml.

(3) Create the startup class Application. Since the service gateway is also registered with the Eureka server as a Eureka client, all client code is almost identical to the above “client” and is no exception here, so the code is no longer given.

(4) Create HelloController class in Eurekaclient. This class is the controller in Spring MVC:

@restController public Class Hellocontroller {@requestMapping ("index")public String index(){return" This is a Eurekaclient" ; }}Copy the code

In the code above, we define an HTTP request method called index that can be accessed by an external environment (such as a browser) using the index address.

Then test it out.

(1) Start eurekaserver, Eurekaclient and L Gateway respectively.

(2) according to the rules of the said before, through the browser to access localhost: 8080 / EUREKACLIENT/index, can see the interface as shown in figure 4 to 10.

This is the simplest project you can create based on the Spring Cloud architecture to learn how to create a registry, register clients with the registry, and request client-defined interfaces through the Gateway.

Later in the book, we will take a closer look at the various components of Spring Cloud and apply them to practical applications.

summary

In this article, we’ll get into Spring Cloud. Any technology primer starts with Hello World, and this article is no exception.

This article first introduces the basic concepts of Spring Cloud, the advantages and disadvantages of Spring Cloud, and its current development status. Then, a simple example of Spring Cloud demonstrates some of its core ideas, namely service registration and discovery, service gateway. This provides readers with a preliminary understanding of Spring Cloud and lays a foundation for subsequent project development.

Three things to watch ❤️

If you find this article helpful, I’d like to invite you to do three small favors for me:

  1. Like, forward, have your “like and comment”, is the motivation of my creation.

  2. Follow the public account “Java rotten pigskin” and share original knowledge from time to time.

  3. Also look forward to the follow-up article ing🚀

  4. [666] Scan the code to obtain the learning materials package