Article directory
foreword
This article introduces Spring Cloud from spring and springboot, and then introduces Spring Cloud Alibaba. And how to quickly get started with Spring Cloud Alibaba: Spring Cloud Alibaba Core Technology and Practical Cases
Spring Cloud
etc. Before we dive into Spring Cloud, let's have a look at Spring and Spring Boot.
Spring framework
We all know that the Spring framework has been around for a long time and it provides the following features:
- Spring JDBC
- Spring MVC
- Spring Security
- Spring AOP
- Spring ORM (mapping with Hibernate)
- Spring Test
Through these features, Java developers used to use Spring MVC to develop web applications and then connect the Spring application with any ORM framework such as Hibernate.
In that era, we used JSP pages to call Spring Controller to call the Service layer that interacted with the database. Then we need to run a standalone web server (such as tomcat) and put the war/ear file into tomcat to run our web application.
Many years ago, there was a famous interview question:
"How to integrate Spring with Hibernate?" - We all know we need to do the following steps:
- Create the applicationtoncontext.xml file
- Declare data source and provide configuration
- Declare a Hibernate Session Factory and associate it with a data source
- Finally, the Session Factory is mapped to the HibernateTemplate of the Spring framework
. After these configurations, Spring and Hibernate can work seamlessly.
Spring Boot
Spring framework has a lot of features and it is a powerful framework that is widely used by Java developers. But as we discussed above, it still has some drawbacks. The world is moving towards loosely coupled architecture to use any pluggable front-end framework like Angular, React etc. but Spring framework is tightly coupled with Spring MVC using JSP pages.
Then came the Spring Boot framework, which is used to quickly build REST APIs related to any UI framework plugin. It also addresses all the shortcomings of the Spring framework by providing the following features:
- Embedded Tomcat server
- Spring Data JPA (automatically connects Hibernate without any configuration)
- Automatic logging for the default logger
- Global exception handler (using AOP to handle exceptions)
- automatic configuration
- In-memory database (great for executing unit test cases)
- Starter dependencies
After the evolution of Spring Boot and microservices, the usage of the traditional Spring framework has decreased and almost every organization has migrated to Spring Boot, which is the modern way of developing production-grade Java web applications.
Spring Cloud
Now let's look at the Spring Cloud realm. As discussed earlier, Spring Boot is used to write standalone Java web applications. So how to configure it to work with external systems or components? The answer is Spring Cloud . Yes, you heard that right.
Spring Cloud provides the following features that are critical for modern distributed systems:
-
Distributed/versioned configuration
A centralized configuration server is used to maintain application configuration
This can be maintained separately from the code repository and is easy to manage -
Service Registration and Discovery
All services register their identity with a registry server, the most famous of which is Eureka.
Clients connected to the central server can update and retrieve addresses. -
Inter-service calls
Services can discover each other to communicate with each other through the following steps:- registration service
- get registration form
- Find downstream services
- Resolve the underlying IP address
- Call REST endpoints using RestTemplate
-
Load Balancing
The goal of load balancing is to maximize throughput, minimize response time, increase efficiency and optimize resource usage.
Using multiple components with load balancing increases reliability and availability through redundancy.
Eureka dependencies have a built-in load balancer called Ribbon, which balances the load across instances of a single service. -
Circuit breakers
are used as a fallback mechanism when calls to another microservice/another system's API fail.
They make it possible to turn circuits on and off and what to do in case of failure. Circuit breakers handle these failures gracefully.
A widely used circuit breaker in Spring Boot is resilience4j. -
API Gateway
Spring Cloud Gateway is an API gateway designed for Spring Boot applications. It has the following functions:- Built on Spring Framework 5, Project Reactor and Spring Boot 2.0
- Ability to match routes based on any request attribute
- Predicates and filters are specific to routes
- Circuit breaker integration
- Spring Cloud Discovery Client集成
- Easy to write predicates and filters
- request rate limit
- path rewriting
-
Spring Cloud Security
Spring Security integration, providing authentication and authorization
Support JWT token verification
Spring Cloud Security provides a set of basic functions for building secure applications by using Spring Boot and Spring Security OAuth2
We can quickly create and implement single sign-on, Systems for common patterns such as token relay and token exchange. -
Distributed Tracing
Tracing is very useful in microservices because requests from clients may be passed between multiple microservices. It is critical for developers to see the state of requests as they move between services, and Spring Cloud addresses this by providing the following dependencies.
We can add the Spring Cloud Sleuth library to our project to enable tracing. Sleuth is responsible for recording time and generating request IDs for latency analysis. With this request ID, we can track how the request passed between services.
Zipkin is a distributed tracing tool designed for analyzing latency issues within microservice architectures. It exposes HTTP endpoints for collecting input data. If we need to add tracing functionality to our project, we should add the spring-cloud-starter-Zipkin dependency. -
Distributed messaging
Spring Cloud Bus connects the nodes of the distributed system through a lightweight message broker. AMQP and other messaging protocols can then be used to broadcast state changes in the application.
This is a very common use case in microservices, enabling asynchronous communication by pushing messages to RabbitMQ, Kafka, AWS SQS, etc.
Spring Cloud Stream is another framework in Spring Cloud for building highly scalable event-driven microservices connected with shared messaging systems. It is used for stream processing.
As we have seen above, Spring Cloud has many features for distributed system communication, we can include the required dependencies and use it very easily.
In a nutshell, Spring Boot is the application used to develop standalone microservice applications, while Spring Cloud is used to configure the communication between these services . Therefore, to implement a production-grade microservices system, both are required.
Spring Cloud Alibaba
As the big steward of microservices, Spring Cloud can manage many microservices, so it needs many small assistants to help.
pring Cloud Alibaba is committed to providing a one-stop solution for microservice development. This project contains the necessary components to develop distributed application microservices, so that developers can easily use these components to develop distributed application services through the Spring Cloud programming model.
components
-
Sentinel: takes traffic as an entry point, and protects the stability of services from multiple dimensions such as traffic control, circuit breaker degradation, and system load protection.
-
Nacos: A dynamic service discovery, configuration management and service management platform that makes it easier to build cloud-native applications.
-
RocketMQ: An open source distributed messaging system, based on highly available distributed cluster technology, provides low-latency, highly reliable message publishing and subscription services.
-
Seata: Alibaba's open source product, an easy-to-use high-performance microservice distributed transaction solution.
-
Alibaba Cloud OSS: Alibaba Cloud Object Storage Service (OSS for short) is a massive, secure, low-cost, and highly reliable cloud storage service provided by Alibaba Cloud. You can store and access any type of data in any application, anytime, anywhere.
-
Alibaba Cloud SchedulerX: A distributed task scheduling product developed by the Alibaba middleware team, which provides second-level, accurate, highly reliable, and highly available scheduled (based on Cron expression) task scheduling services.
-
Alibaba Cloud SMS: SMS service covering the world, friendly, efficient, and intelligent interconnected communication capabilities, helping enterprises quickly build customer access channels.
How to use How to introduce dependencies
If you need to use the released version, add the following configuration in dependencyManagement.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2022.0.0.0-RC2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Then add the dependencies you need to use in dependencies to use.
How to Master Spring Cloud Alibaba
In order to let everyone quickly get started with Spring Cloud Alibaba, I recommend a book "Spring Cloud Alibaba Core Technology and Practical Cases"
Jingdong link: https://item.jd.com/14010448.html
feature
No omissions: comprehensive coverage of Dubbo's core knowledge points
Directly hit the key points: precise positioning of technical details in actual combat cases
Apply what you have learned: concise demonstrations ensure that development and learning are not out of touch Subtle
influence: grinding knowledge explanations penetrate technical points
to improve efficiency: vertical technical refinement No detours
, step-by-step improvement: progressive arrangement of knowledge points to ensure coherence
Supporting resources: free case source files of the whole book to help learning
brief introduction
This book starts from the basic concepts of distributed systems, and gradually deepens the advanced practice of distributed system middleware Spring Cloud Alibaba. It focuses on the complete process of integrating various distributed components using the Spring Cloud Alibaba framework, so that readers can not only systematically Learn the relevant knowledge of distributed middleware,
but also have a deeper understanding of business logic analysis ideas and practical application development.
The book is divided into 5 chapters. The opening part of Chapter 1 explains the evolution process of distributed systems, the overview of Spring Cloud Alibaba and the selection of versions, as well as the advantages and disadvantages of single architecture/microservice architecture;
Chapter 2 explains how to use Spring Cloud Alibaba to implement RPC communication;
In Chapter 3, when introducing mainstream Nacos components, it introduces the concept of ternary and the use of Nacos to realize the registration center and configuration center, including core technologies such as dynamic switching of environments, dynamic refresh of configurations, general-purpose configurations, and version rollbacks. The service environment provides the underlying architecture;
Chapter 4 introduces the Sentinel components responsible for current limiting and circuit breaker degradation, including collection system operating status, flow control, circuit breaker degradation, hotspots, authorization, system rules, exception handling for flow control, exception handling for circuit breakers, and rule persistence;
Chapter 5 introduces common cases of gateways, as well as frequently used technical points commonly used in software projects, and strives to provide a shortcut for quick learning for programmers developing microservice projects.
The content of this book is from shallow to deep, with clear structure, rich examples, easy to understand, and strong practicability. It is suitable for those who need to learn Spring Cloud Alibaba related technologies in an all-round way, and it is also suitable for training schools as training materials. Teaching reference books for related majors.
Take RocketMQ as an example
RocketMQ is an open source distributed messaging system, based on highly available distributed cluster technology, providing low-latency, highly reliable message publishing and subscription services.
Download and start RocketMQ
Before accessing RocketMQ Binder, you first need to start RocketMQ's Name Server and Broker.
-
Download the latest binary file of RocketMQ and unzip it
-
Start Name Server
sh bin/mqnamesrv
- Start Broker
sh bin/mqbroker -n localhost:9876
Introduce dependencies
Modify pom.xml
the file to import RocketMQ Stream Starter.
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>
simple example
Create Topics
sh bin/mqadmin updateTopic -n localhost:9876 -c DefaultCluster -t test-topic
sample code
Configure the Binding information of Input and Output and cooperate with @EnableBinding
annotations to make it effective
@SpringBootApplication
@EnableBinding({
Source.class, Sink.class })
public class RocketMQApplication {
public static void main(String[] args) {
SpringApplication.run(RocketMQApplication.class, args);
}
}
Configure Binding information:
# 配置rocketmq的nameserver地址
spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
# 定义name为output的binding
spring.cloud.stream.bindings.output.destination=test-topic
spring.cloud.stream.bindings.output.content-type=application/json
# 定义name为input的binding
spring.cloud.stream.bindings.input.destination=test-topic
spring.cloud.stream.bindings.input.content-type=application/json
spring.cloud.stream.bindings.input.group=test-group
application start
- Add configuration, add basic configuration information in /src/main/resources/application.properties of the application
spring.application.name=rocketmq-example
server.port=28081
-
Start the application, support IDE to start directly and start after compiling and packaging.
- IDE starts directly: find the main class
RocketMQApplication
and execute the main method to start the application. - Start after packaging and compiling: first execute
mvn clean package
to compile and package the project, and then executejava -jar rocketmq-example.jar
to start the application.
- IDE starts directly: find the main class
message processing
Use the binding whose name is output to send a message to the topic test-topic.
Subscribe to data using 2 input bindings.
-
input1: Subscribe to messages whose topic is test-topic, and consume all messages sequentially (the premise of sequential consumption is that all messages are in a MessageQueue)
-
input2: Subscribe to the message whose topic is test-topic, asynchronously consume the message whose tags are tagStr, and the number of consumer-side thread pools is 20
The configuration information is as follows:
spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
spring.cloud.stream.bindings.output.destination=test-topic
spring.cloud.stream.bindings.output.content-type=application/json
spring.cloud.stream.bindings.input1.destination=test-topic
spring.cloud.stream.bindings.input1.content-type=text/plain
spring.cloud.stream.bindings.input1.group=test-group1
spring.cloud.stream.rocketmq.bindings.input1.consumer.orderly=true
spring.cloud.stream.bindings.input2.destination=test-topic
spring.cloud.stream.bindings.input2.content-type=text/plain
spring.cloud.stream.bindings.input2.group=test-group2
spring.cloud.stream.rocketmq.bindings.input2.consumer.orderly=false
spring.cloud.stream.rocketmq.bindings.input2.consumer.tags=tagStr
spring.cloud.stream.bindings.input2.consumer.concurrency=20
send message
Use MessageChannel for message sending:
public class ProducerRunner implements CommandLineRunner {
@Autowired
private MessageChannel output; // 获取name为output的binding
@Override
public void run(String... args) throws Exception {
Map<String, Object> headers = new HashMap<>();
headers.put(MessageConst.PROPERTY_TAGS, "tagStr");
Message message = MessageBuilder.createMessage(msg, new MessageHeaders(headers));
output.send(message);
}
}
Or use RocketMQ's native API to send messages:
public class RocketMQProducer {
DefaultMQProducer producer = new DefaultMQProducer("producer_group");
producer.setNamesrvAddr("127.0.0.1:9876");
producer.start();
Message msg = new Message("test-topic", "tagStr", "message from rocketmq producer".getBytes());
producer.send(msg);
}
message reception
Receive messages using @StreamListener
annotations:
@Service
public class ReceiveService {
@StreamListener("input1")
public void receiveInput1(String receiveMsg) {
System.out.println("input1 receive: " + receiveMsg);
}
@StreamListener("input2")
public void receiveInput2(String receiveMsg) {
System.out.println("input2 receive: " + receiveMsg);
}
}