Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring Cloud-based micro-service architecture

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use the Spring Cloud-based micro-service architecture". In the daily operation, I believe many people have doubts about how to use the Spring Cloud-based micro-service architecture. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the Spring Cloud-based micro-service architecture". Next, please follow the editor to study!

Overview

Micro services are service units that can be deployed independently, scale horizontally, and accessed independently (or have independent databases), while Spring Cloud is an orderly collection of a series of frameworks used to manage micro services. Taking advantage of the development convenience of Spring Boot, Spring Cloud cleverly simplifies the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, etc., which can be started and deployed with one click with the development style of Spring Boot.

Spring Cloud does not repeat the wheels, but combines the more mature service frameworks developed by various companies that can stand the actual test, and re-encapsulates them in Spring Boot style, shielding out complex configuration and implementation principles, and finally provides developers with a set of distributed system development kits that are easy to understand, easy to deploy and easy to maintain.

Spring Cloud has many components, among which the core components are: Eureka (registry), Hystrix (circuit breaker), Config (configuration center), Zuul (agent, gateway) and so on.

Next, we might as well use a few demo to understand how Spring Cloud is built step by step.

Sample source code, please stamp the source code.

How to build Eureka

How to build Hystrix

How to build Config

How to build Zuul

Introduction to how to build Eureka components

Registry Eureka is a REST-based service for mutual discovery between services. Any service that needs support from other services needs to be obtained through it; similarly, all services need to be registered here to facilitate future invocation by other services. The advantage of Eureka is that you don't need to know what service to look for, you just need to go to the registry to get it, and you don't need to know where the supported service is and how many services support it, just come here and get it. In this way, it improves the stability and reduces the difficulty of building micro-service architecture.

Project description

Call service A normally and request service B:

After having the service center, service A cannot invoke service B directly, but AMagi B invokes service B through the registry by registering the service and then discovering each other.

The above is just the mutual invocation between the two services. If there are more than a dozen or even dozens of services, any project change may involve the restart of several projects, which is troublesome and error-prone. Get the service through the registry, you do not need to pay attention to the IP address of the project you call, it is composed of several servers, and you can go directly to the registry to get the available services to call.

Deploy to the cloud gang registration service

1. Add dependencies to pom

Org.springframework.cloud spring-cloud-starter org.springframework.cloud spring-cloud-starter-eureka-server org.springframework.boot spring-boot-starter-test test

2. Add @ EnableEurekaServer annotation to the startup code

@ SpringBootApplication@EnableEurekaServerpublic class SpringCloudEurekaApplication {public static void main (String [] args) {SpringApplication.run (SpringCloudEurekaApplication.class, args);}}

3. Configuration file

By default, the service registry will also try to register itself as a client, so we need to disable its client registration behavior and add the following configuration to application.properties:

Spring.application.name=spring-cloud-eurekaserver.port=8000eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.client.serviceUrl.defaultZone= http://localhost:${server.port}/eureka/

Eureka.client.register-with-eureka: indicates whether to register yourself with Eureka Server. The default is true.

Eureka.client.fetch-registry: indicates whether to obtain registration information from Eureka Server. Default is true.

Eureka.client.serviceUrl.defaultZone: set the address to interact with Eureka Server, which both the query service and registration service depend on. The default is http://localhost:8761/eureka; multiple addresses can be used and separated.

After starting the project, visit: http://localhost:8000/, you can see the following page, in which no services have been found

Service provider (B)

1. Pom package configuration

Create a springboot project and add the following configuration to pom.xml:

Org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-test test

2. Configuration file

The application.properties configuration is as follows:

Spring.application.name=spring-cloud-producerserver.port=9000eureka.client.serviceUrl.defaultZone= http://localhost:8000/eureka/

3. Startup class

Add @ EnableDiscoveryClient annotation to the startup class

@ SpringBootApplication@EnableDiscoveryClientpublic class ProducerApplication {public static void main (String [] args) {SpringApplication.run (ProducerApplication.class, args);}}

4. Service provision

Provide hello services:

@ RestControllerpublic class HelloController {@ RequestMapping ("/ hello") public String index (@ RequestParam String name) {return "hello" + name+ ", this is first messge";}}

With the addition of the @ EnableDiscoveryClient annotation, the project has the ability to register for services. After you start the project, you can see the SPRING-CLOUD-PRODUCER service on the registry page.

At this point, the service provider configuration is complete.

Service consumers (A)

1. Pom package configuration

Consistent with the service provider

Org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-test test

2. Configuration file

The application.properties configuration is as follows:

Spring.application.name=spring-cloud-consumerserver.port=9001eureka.client.serviceUrl.defaultZone= http://localhost:8000/eureka/

3. Startup class

Add @ EnableDiscoveryClient and @ EnableFeignClients annotations to the startup class:

@ SpringBootApplication@EnableDiscoveryClient@EnableFeignClientspublic class ConsumerApplication {public static void main (String [] args) {SpringApplication.run (ConsumerApplication.class, args);}}

@ EnableDiscoveryClient: enable service registration and discovery

@ EnableFeignClients: enable feign to make remote calls

Feign is a declarative Web Service client. Using Feign makes it easier to write Web Service clients by defining an interface and then adding annotations to it, as well as supporting JAX-RS standard annotations. Feign also supports pluggable encoders and decoders. Spring Cloud encapsulates Feign to support Spring MVC standard annotations and HttpMessageConverters. Feign can be used in combination with Eureka and Ribbon to support load balancing.

4. Feign call implementation

FeignClient (name= "spring-cloud-producer") public interface HelloRemote {@ RequestMapping (value = "/ hello") public String hello (@ RequestParam (value = "name") String name);}

Name: remote service name, and the name of the spring.application.name configuration

The method names and parameters in this class need to be the same as those in the contoller in the remote service.

5. Web layer invokes remote service

Inject HelloRemote into the controller layer and call it as usual.

@ RestControllerpublic class ConsumerController {@ Autowired HelloRemote HelloRemote; @ RequestMapping ("/ hello/ {name}") public String index (@ PathVariable ("name") String name) {return HelloRemote.hello (name);}}

At this point, the simplest example of service registration and invocation is complete.

test

Start three projects: spring-cloud-eureka, spring-cloud-producer and spring-cloud-consumer in turn.

First enter: http://localhost:9000/hello?name=neo to check whether the spring-cloud-producer service is normal

Return: hello neo,this is first messge

This indicates that spring-cloud-producer starts normally and the services provided are normal.

Enter: http://localhost:9001/hello/neo in browser

Return: hello neo,this is first messge

It indicates that the client has successfully called the remote service hello through feign and returned the result to the browser.

If {{site.data.alerts.callout_danger}} is deployed in the cloud gang, the following three points must be guaranteed for verification:

The port enables external access.

Consumer is associated with producer

Hello?name=neo and hello/neo are added after accessing the resulting url

After that, the verification of the component is the same.

Introduction to how to build Hystrix components

In micro-service architecture, there are usually multiple service layer invocations, and the failure of basic services may lead to cascade failures, resulting in the unavailability of the whole system, which is called service avalanche effect. This problem can be avoided by using Hystrix (fuses).

The principle of a fuse is simple, like an electric overload protector. It can achieve rapid failure, and if it detects many similar errors in a period of time, it will force multiple subsequent calls to fail quickly and no longer access the remote server, thus preventing the application from constantly trying to perform operations that may fail, making the application continue to execute without waiting for the error to be corrected, or wasting CPU time waiting for a long timeout to occur. The fuse also enables the application to diagnose whether the error has been corrected, and if so, the application will try to invoke the operation again.

When the number of Hystrix Command requests for back-end service failures exceeds a certain percentage (the default is 50%), the circuit breaker will switch to the open state (Open). At this point, all requests will fail directly and will not be sent to the back-end service. After keeping the circuit breaker in the open state for a period of time (default 5 seconds), the circuit breaker automatically switches to the semi-open state (HALF-OPEN). At this time, the return of the next request will be judged, and if the request is successful, the circuit breaker will switch back to the closed-circuit state (CLOSED), otherwise it will switch back to the open-circuit state (OPEN). Hystrix's circuit breaker is like a fuse in our home circuit. Once the back-end service is not available, the circuit breaker will directly cut off the request chain to avoid sending a large number of invalid requests affecting the system throughput, and the circuit breaker has the ability to self-detect and recover.

Project description

To achieve the circuit breaker effect by adding Hystrix components to the service consumer, you only need to add Hystrix to the demo foundation of Eureka.

Hystrix acts on the service invocation side, so it needs to be added to A.

Deploy to RainbondHystrix service

Because the circuit breaker only acts on the service invocation side, we only need to change the consumer (A) service-related code according to the sample code in the previous article. Because Hystrix is already dependent on Feign, there is no need to make any changes to the maven configuration.

1. Add this entry to the configuration file application.properties:

Feign.hystrix.enabled=true

2. Create a callback class

Create a method for HelloRemoteHystrix class inheritance and HelloRemote to implement callback:

@ Componentpublic class HelloRemoteHystrix implements HelloRemote {@ Override public String hello (@ RequestParam (value = "name") String name) {return "hello" + name+ ", this messge send failed";}}

3. Add fallback attribute

Add the specified fallback class to the HelloRemote class and return the contents of the fallback class in the event of a service breaker:

FeignClient (name= "spring-cloud-producer", fallback = HelloRemoteHystrix.class) public interface HelloRemote {@ RequestMapping (value = "/ hello") public String hello (@ RequestParam (value = "name") String name);}

4. Test

Then let's test it and see the effect.

Start three projects: spring-cloud-eureka, spring-cloud-producer and spring-cloud-consumer in turn.

Enter: http://localhost:9001/hello/neo in browser

Return: hello neo,this is first messge

It shows that the normal access will not be affected after adding the information related to the circuit breaker. Next, let's manually stop the spring-cloud-producer project and test again:

Enter: http://localhost:9001/hello/neo in browser

Return: hello neo, this messge send failed

The circuit breaker is successful according to the returned result.

Introduction to how to build Config components

With the growing size of online projects, each project is scattered with a variety of configuration files. If the distributed development model is adopted, the required configuration files will continue to increase with the increase of services. The change of a certain basic service information will cause a series of updates and restarts, which is not convenient for the maintenance of the project, and Spring Cloud Config is to solve this problem.

Business description

Config currently supports git and svn as repositories for configuration files. In this example, git repository is used to store configuration files. Config-client here is equivalent to Service An and Service B. their configuration files are stored centrally, and their respective configuration files are obtained through Config-server.

Deploy to Rainbondgit warehouse

First, a folder config-repo is created on github to store configuration files. In order to simulate the production environment, we create the following three configuration files:

/ / Development environment neo-config-dev.properties// test environment neo-config-test.properties// production environment neo-config-pro.properties

A property neo.hello is written in each configuration file, and the value of the property is hello im dev/test/pro. Let's start configuring the server side.

# config-server

1. Add dependencies

Org.springframework.cloud spring-cloud-config-server

You just need to add a spring-cloud-config-server package reference.

2. Configuration file

Server: port: 8040spring: application: name: spring-cloud-config-server cloud: config: server: git: uri: https://github.com/xxx # configure the address of the git repository search-paths: config-repo # relative address under the git warehouse address You can configure multiple, use, split. Username: # account of git warehouse password: # password of git warehouse

Spring Cloud Config also provides a way to store configurations locally. We just need to set the property spring.profiles.active=native,Config Server to retrieve the configuration file from the src/main/resource directory of the application by default. You can also specify the location of the configuration file through the spring.cloud.config.server.native.searchLocations=file:E:/properties/ property. Although Spring Cloud Config provides such functionality, git is recommended to support better content management and version control.

3. Startup class

Add @ EnableConfigServer to the startup class to activate support for configuration center

@ EnableConfigServer@SpringBootApplicationpublic class ConfigServerApplication {public static void main (String [] args) {SpringApplication.run (ConfigServerApplication.class, args);}}

By this time, the relevant configuration on the server side has been completed.

4. Test the server side

First of all, we need to test whether the server can read the configuration information on github and visit http://localhost:8001/neo-config/dev directly.

The returned information is as follows:

{"name": "neo-config", "profiles": ["dev"], "label": null, "version": null, "state": null, "propertySources": [{"name": "https://github.com/goodrain-apps/spring-cloud-demo/config-repo/neo-config-dev.properties"," "source": {"neo.hello": "hello im dev update"}]}

The information returned above contains the location and version of the configuration file, the name of the configuration file and the specific contents of the configuration file, indicating that the server has successfully obtained the configuration information of the git repository.

If you directly view the configuration information in the configuration file, you can visit: http://localhost:8001/neo-config-dev.properties, return: neo.hello: hello im dev

Modify the configuration information in the configuration file neo-config-dev.properties to: neo.hello=hello im dev update, visit http://localhost:8001/neo-config-dev.properties in the browser again, and return: neo.hello: hello im dev update. Indicates that the server will automatically read the latest submission

The configuration files in the repository will be converted into web interfaces. You can refer to the following rules for access:

/ {application} / {profile} [/ {label}]

/ {application}-{profile} .yml

/ {label} / {application}-{profile} .yml

/ {application}-{profile} .properties

/ {label} / {application}-{profile} .properties

Take neo-config-dev.properties as an example, its application is neo-config,profile and dev. Client will choose to read the corresponding configuration based on the entered parameters.

# Config-client

Mainly shows how to obtain the configuration information of the server side in the business project

1. Add dependencies

Org.springframework.cloud spring-cloud-starter-config org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test

Introducing spring-boot-starter-web package to facilitate web testing

2. Configuration file

You need to configure two configuration files, application.properties and bootstrap.properties

Application.properties is as follows:

Spring.application.name=spring-cloud-config-clientserver.port=8002

Bootstrap.properties is as follows:

Spring.cloud.config.name=neo-configspring.cloud.config.profile=devspring.cloud.config.uri= http://localhost:8001/spring.cloud.config.label=master

Spring.application.name: corresponds to the {application} section

Spring.cloud.config.profile: corresponds to the {profile} section

Spring.cloud.config.label: the branch of the corresponding git. This parameter is useless if the configuration center is using local storage

Spring.cloud.config.uri: the specific address of the configuration center

Spring.cloud.config.discovery.service-id: specify the service-id of the configuration center to facilitate expansion to a highly available configuration cluster.

The above spring-cloud-related properties must be configured in bootstrap.properties for parts of the config to be loaded correctly. Because the relevant configuration of config precedes application.properties, and bootstrap.properties loads before application.properties.

3. Startup class

Add @ EnableConfigServer to the startup class to activate support for configuration center

@ SpringBootApplicationpublic class ConfigClientApplication {public static void main (String [] args) {SpringApplication.run (ConfigClientApplication.class, args);}}

The startup class only needs the @ SpringBootApplication annotation.

4. Web test

Use the @ Value annotation to get the value of the server parameter

@ RestControllerclass HelloController {@ Value ("${neo.hello}") private String hello; @ RequestMapping ("/ hello") public String from () {return this.hello;}}

After starting the project, visit: http://localhost:8002/hello, return: hello im dev update indicates that the parameters have been correctly obtained from the server. This is a complete server that provides configuration services, and the example of the client getting configuration parameters is complete.

Introduction to how to build Zuul components

In the micro-service architecture, the back-end service is often not directly open to the caller, but is routed to the corresponding service through an API gateway according to the requested url. When an API gateway is added, a wall is created between the third-party caller and the service provider, which communicates with the caller directly for permission control, and then distributes the request evenly to the backend server. The component used for agent scheduling is Zuul.

Project description

In the project, only Zuul provides external access, and Gateway dispatches requests to different backend services depending on the url of the request.

Deploy to RainbondGateway

1. Add dependencies

Org.springframework.cloud spring-cloud-starter-zuul

Introduction of spring-cloud-starter-zuul package

2. Configuration file

The configuration here in spring.application.name=gateway-service-zuulserver.port=8888# indicates that access / producer/** is directly redirected to the http:// domain name / * * zuul.routes.baidu.path=/producer/**zuul.routes.baidu.url=http:// domain name /

3. Startup class

@ SpringBootApplication@EnableZuulProxypublic class GatewayServiceZuulApplication {public static void main (String [] args) {SpringApplication.run (GatewayServiceZuulApplication.class, args);}}

Add @ EnableZuulProxy to the startup class to support gateway routing.

4. Test

To start the gateway-service-zuul-simple project, type: http://localhost:8888/producer/hello?name=neo first

Return: hello neo,this is first messge

It indicates that the scheduling is successful.

At this point, the study on "how to use the Spring Cloud-based micro-service architecture" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report