Theoretical basis of Spring Cloud

Eureka Server registry is set up

Single-node construction

  1. File -> new -> project Create a new project and change the image: start.aliyun.com

  1. Enter maven configuration

  1. Select the Eureka Server dependencies, then Next select the file path, ok, and wait for the project dependencies to complete loading

  1. Annotate the startup class with @enableeurekaserver to indicate that this is a registry server

    package com.park.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * @author BarryLee */@EnableEurekaServer@SpringBootApplicationpublic class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); }}

  2. Change the application.properties configuration file to application.yml

    server: port: 7900eureka: client: Register-with-eureka: register with Eureka: register with Eureka: register with Eureka: register with Eureka False # Whether to obtain registration information from Eureka server, because there is only one node, there is no need to synchronize data of other nodes, use false fetch-registry: false service-url: # set the URL of the service registry, for the client and server side ac defaultZone: http://localhost:7900/eureka/

  3. Start, then open http://localhost:7900/

The HA cluster is set up

  1. Change the hosts file in win10 to C:\Windows\System32\drivers\etc

    Refer to the article: modify the hosts failure blog.csdn.net/Zandysjtu/a…

    Add 127.0.0.1 eureka-7900127.0.0.1 eureka-7901127.0.0.1 eureka-7902 to the end of the host file

  2. Add a configuration file application-eureka-7900.yml based on the above operations

    server: port: 7900eureka: client: Register-with-eureka: register with Eureka: register with Eureka: register with Eureka: register with Eureka True # Whether to obtain registration information from Eureka server, because there is only one node, there is no need to synchronize data of other nodes, use false fetch-registry: true service-url: # set the URL of the service registry, for the client and server side ac defaultZone: http://eureka-7901:7901/eureka/, http://eureka-7902:7902/eureka/ instance: Hostname: eureka-7900

  3. application-eureka-7901.yml

    server: port: 7901eureka: client: Register-with-eureka: register with Eureka: register with Eureka: register with Eureka: register with Eureka True # Whether to obtain registration information from Eureka server, because there is only one node, there is no need to synchronize data of other nodes, use false fetch-registry: true service-url: # set the URL of the service registry, for the client and server side ac defaultZone: http://eureka-7900:7900/eureka/, http://eureka-7902:7902/eureka/ instance: hostname: eureka-7901

  4. application-eureka-7902.yml

    server: port: 7902eureka: client: Register-with-eureka: register with Eureka: register with Eureka: register with Eureka: register with Eureka True # Whether to obtain registration information from Eureka server, because there is only one node, there is no need to synchronize data of other nodes, use false fetch-registry: true service-url: # set the URL of the service registry, for the client and server side ac defaultZone: http://eureka-7900:7900/eureka/, http://eureka-7901:7901/eureka/ instance: hostname: eureka-7902

  5. Close the original single-node service, Edit Configurations…

  1. Select EurekaServerApplication to copy three; Change Name for all three and specify Active profiles

    Unavaliable: http://localhost:7900/, unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable: unavaliable

Eureka Client build

  1. Open Project Structure and select Module

  2. Add a new Module consumer

  3. Add dependencies Spring Web and Eureka Client, then Next select the file path, confirm, and wait for the project dependencies to complete loading

  1. And then the project should look something like that

  2. Add the @enableeurekaclient annotation to the startup class to indicate that this is a registry client

    package com.park.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author BarryLee */@EnableEurekaClient@SpringBootApplicationpublic class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}

  3. Change the configuration file application.properties to application.yml

    server: port: 8800spring: application: name: consumereureka: client: register-with-eureka: true service-url: defaultZone: http://localhost:7900/eureka/

  4. Start the service and open http://localhost:7900/, http://localhost:7901/, and http://localhost:7902/ respectively to see that the consumer has successfully registered with the registry

OpenFeign declarative service invocation

  1. Prepare a Provider service. Use the same method to build a provider service (as a common API side, such as a service that sends various messages) : introduce web and Discover Client dependencies; Add the @enableeurekaclient annotation to the startup class;

    Modify the configuration file as follows

    Client: register-with-eureka: Client: register-with-eureka: true service-url: defaultZone: http://localhost:7900/eureka/

Start the service, open Eureka, and see that the provider is registered

  1. Provider adds lombok dependencies

    Org. Projectlombok lombok 1.18.8

  2. The Provider service adds two classes

The MsgController class is used to handle requests from consumers

package com.park.provider.controller; import com.park.provider.domain.Email; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author BarryLee */@RestController@RequestMapping("/msg")public class MsgController { @PostMapping("/sendEmail") Public Email sendEmail(@requestBody Email Email) {system.out.println ("provider receives Email: "+ Email); Email.setcontent (" Secretly change the content "); return email; }} package com.park.provider.domain; import lombok.Data; /** * @author BarryLee */@Datapublic class Email { private String email; private String content; }Copy the code
  1. Consumer introduces the OpenFeign component

    Org. Springframework. Cloud spring – the cloud – starter – openfeign org. Projectlombok lombok 1.18.8

  2. Add an annotation to the consumer startup class: @enableFeignClients

  3. Add a few classes for consumer, Email and Provider

package com.park.consumer.domain; import lombok.Data; /** * @author BarryLee */@Datapublic class Account { private Integer id; private String username; private String password; private String email; } package com.park.consumer.api; import com.park.consumer.domain.Email; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; /** * All annotations to this class are for Feign, It will assemble an HTTP request based on the annotations here * annotation FeignClient annotates the service name * @author BarryLee */ @feignClient (name = "provider")public interface MsgApi {/** * OpenFeign, It can support SpringMVC annotations * send mail */ @postMapping ("/ MSG /sendEmail") Email sendEmail(@requestBody Email Email); } package com.park.consumer.controller; import com.netflix.discovery.converters.Auto; import com.park.consumer.api.MsgApi; import com.park.consumer.domain.Account; import com.park.consumer.domain.Email; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author BarryLee */@RestController@RequestMapping("/account")public class AccountController { @Autowired private MsgApi msgApi; @postmapping ("/register") public Account register(@requestBody Account register) {system.out.println (" Consumer receives registration request: " + account); Email email = new Email(); email.setEmail(account.getEmail()); Email.setcontent (" open the url XXX and activate your account "); // Call final Email with OpenFeign res = msgapi.sendemail (Email); System.out.println(" The consumer receives the result from the provider: "+ res); account.setId(222); return account; }}Copy the code
  1. Test the OpenFeign call by sending a POST request using Postman

Consumer console output

The consumer receives the registration request: Account(ID = NULL, username= YYYY, Password = EEee, [email protected]) Email(Email [email protected], content= secretly change the content)Copy the code

Provider console output

Provider receives Email: Email(Email [email protected], content= open the website XXX, activate your account oh)Copy the code

Postman makes a request to the consumer, and the consumer receives the request and sends it to the provider using OpenFeign

Ribbon Client load balancing

Default Load Policy

  1. OpenFeign already integrates the Ribbon component. If this is correct, a polling algorithm is already in effect. So let’s verify that

  2. Add two configuration files to the Provider service, application-8901.yml configured as follows

    server: port: 8901​spring: application: name: provider​eureka: client: register-with-eureka: true service-url: defaultZone: http://localhost:7900/eureka/

  3. Application-8902. Yml is the same as 8901. You can change the port number to 8902

  4. Configure these two configuration files for the provider in the EditConfiguration of the IDEA

  5. The MsgController class of provider is modified as follows

    @Value("${server.port}") private String port; @postMapping ("/sendEmail") Public String sendEmail(@requestBody Email Email) {system.out.println ("provider port: " + port); System.out.println("provider receives mail: "+ email); Email.setcontent (" Secretly change the content "); return port; }Copy the code
  6. The MsgApi for consumer is modified as follows

    @PostMapping("/msg/sendEmail")    String sendEmail(@RequestBody Email email);
    Copy the code
  7. The AccountController for consumer is modified as follows

    @Autowired private MsgApi msgApi; @postmapping ("/register") public Account register(@requestBody Account register) {system.out.println (" Consumer receives registration request: " + account); Email email = new Email(); email.setEmail(account.getEmail()); Email.setcontent (" open the url XXX and activate your account "); // Use OpenFeign to call String res = msgabi.sendemail (email); System.out.println(" Consumer receives provider return port: "+ res); Account.setid (integer.parseint (res)); // Set the id to the port of the provider that is invoked. return account; }Copy the code
  8. Let’s start the test and use Postman to call the interface repeatedly. You can see that the port is polling

Modifying a Load Policy

Modify the configuration file in the consumer, the caller of the service

  1. Example Change the load policy of the service named Provider to random algorithm

    provider: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

  2. Globally, add the following configuration to any spring-managed class, such as the launcher class or the @Component class

    @Beanpublic IRule ribbonRule() { return new RandomRule(); }

The other algorithms are similar

Hystrix fuses, downgrades, current limiting

Feign comes with Hystrix, so there is no need to import packages

FallBack

  1. Consumer is the addition of the service caller profile

    feign: hystrix: enabled: true

  2. Add the class MsgFallBack

package com.park.consumer.fallback; import com.park.consumer.api.MsgApi; import com.park.consumer.domain.Email; import org.springframework.stereotype.Component; /** * @author BarryLee * 1. */ @componentPublic class MsgFallBack implements MsgApi {@override public String sendEmail(Email Email) { System.out.println(" send mail fuse "); return "-1"; }}Copy the code
  1. Modify annotations in the Consumer MsgApi interface

    @FeignClient(name = “provider”, fallback = MsgFallBack.class)

  2. To start the test, try a normal call; Then close the Provider service completely and invoke the/Register interface using Postman

The console prints “Send mail is fushed”; Id becomes minus 1

Open the dashboard

You can do this without it

  1. Consumer introduces dependencies

    org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-netflix-hystrix-dashboard org.springframework.boot spring-boot-starter-actuator

  2. The Consumer start class adds annotations

    @EnableHystrixDashboard@EnableCircuitBreaker

  3. Adding a Configuration file

    If you want to use the Hystrix Dashboard to monitor current services, you need to expose monitoring information management: endpoints: web: exposure: include: “*”

  4. Restart the service, open http://localhost:8800/hystrix

Input: http://localhost:8800/actuator/hystrix.stream

Then you start sending requests using Postman

Zuul gateway

Zuul integrates ribbon and Hystrix by default

To enable the gateway

  1. Add a module zuul, component selection: Web, Eureka Client, Zuul

After the project is created, the directory is as follows

  1. Configuration file application.yml

    server: port: 80spring: application: name: zuuleureka: client: service-url: defaultZone: http://localhost:7900/eureka/

  2. Start the class to add annotations

    @EnableZuulProxy@EnableEurekaClient

  3. Start Zuul and open http://localhost:7900/ to see that Zuul has registered with Eureka. Then use Postman to test the interface

    http://localhost/consumer/account/register

Load strategy

It works like a consumer. Both are Ribbon and are polling policies by default

  1. You can configure a single service as follows. For the overall configuration, see the Ribbon section in the document

    consumer: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

  2. The test. To test this, add the following code in Consumer

    @Value(“${server.port}”) private String port;

    @GetMapping(“/zuul”) public String testZuul() { return port; }

Sending multiple requests can reveal that the load policy has been modified

Hystrix

Zipkin link tracking

  1. Go to the official website to download the server: zipkin.io/

Start java-jar zipkin-server-2.21.5-exec.jar

  1. After the open http://localhost:9411/zipkin/, you can see has been deployed successfully

  2. Add dependencies to the POM of services that require link tracking, such as Zuul, Consumer, and provider

    org.springframework.cloud spring-cloud-starter-zipkin

Add it to the configuration file

Spring: #zipkin Zipkin: base-URL: http://localhost:9411/ # Sampling ratio 1 Sleuth: sampler: Rate: 1Copy the code
  1. Send a request, as already written:

    http://localhost/consumer/account/zuul

    http://localhost/consumer/account/register

  2. At this point, you can already see the request on the Zipkin page

Admin Health Check

  1. To create module admin, check dependencies or add them manually

<! --><dependency> <groupId>de. Codecentric </groupId> <artifactId>spring-boot-admin-starter-server</artifactId></dependency><! <dependency> <groupId>de. Codecentric </groupId> <artifactId>spring-boot-admin-server-ui</artifactId></dependency>Copy the code
  1. Start the class to add annotations

    @EnableAdminServer

  2. Add dependencies to the service POM that needs to be monitored

    Org.springframework. boot spring-boot-starter-actuator 2.2.1 org.springframework.boot spring-boot-starter-actuator

Add in the configuration file

# Report health information to adminSpring: boot: admin: client: URL: http://localhost:6010/# include: "*"Copy the code
  1. Restart the service, open http://localhost:6010/wallboard

Click on it to see details

Generally, the offline service needs to be configured with email or pin messages to use

Config Configuration Center

Server Setup

  1. Add module Config. Use Config Server, Eureka Client, and actuator

The current project structure

  1. Start the class to add annotations

    @EnableConfigServer

  2. The configuration file

    Server: port: 5900Spring: Application: name: config Cloud: config: server: git: uri: github.com/{your git}/con… label: mastereureka: client: service-url: defaultZone: http://localhost:7900/eureka/

Git repository

  1. Create a new repository for git: config-server

  2. Add a new file: consumer-dev.yml

    spring: application: name: consumer boot: admin: client: url: http://localhost:6010/ #zipkin zipkin: base-url: http://localhost:9411/ # Sampling ratio 1 Sleuth: sampler: Rate: 1Eureka: client: register-with-Eureka: true fetch-registry: True service – url: defaultZone: http://localhost:7900/eureka/# change tactics Ribbon load, the provider for specific services of service provider: Ribbon: NFLoadBalancerRuleClassName: com.net flix. Loadbalancer. RandomRule# enable hystrixfeign: hystrix: enabled: True# if you want to monitor the current service, you need to expose the monitoring information management: endpoints: web: exposure: include: “*”#

  3. Open http://localhost:5900/consumer-dev.yml you can see the page shows the consumer in the warehouse – dev. Yml document, also is our configuration center server side ready

Client Configuration

Actuator Refreshing Configuration

This configuration refreshes the configuration of a single node for a single service

  1. For example, for consumer, first of all, spring Cloud Config client is introduced, as well as Actuator dependencies

    org.springframework.cloud spring-cloud-config-client org.springframework.boot spring-boot-starter-actuator

  2. Change the application.yml configuration file to bootstrap.properties

    # configuration center spring. Cloud. Config. Uri = http://localhost:5900#git branch spring. Cloud. Config. The label = master# below two configuration, equivalent to enable the configuration file: Application – test. Yml, Here is the consumer – dev. Yml# application part of the spring. The cloud. Config. The name = consumer# profile part of spring. Cloud. Config. Profile = dev# refresh Allows you to update, * can also be used to expose all endpoints management endpoints. Web. Exposure. Include = *

  3. Add an annotation to the Consumer AccountController class, which updates all @Value annotations for the current class

    @RefreshScope

  4. The AccountController class adds code to test for configuration file updates

    */ @value (“${configText}”)private String configText; @GetMapping(“/testConfig”) public String testConfig() { return configText; }

  5. Start consumer to test if the consumer-dev.yml configuration file is pulled from the configuration center and send a GET request: http://localhost:8800/account/testConfig, returned to the configText that pull a success

  6. Update the configText in the consumer-dev.yml configuration file on Git to park222

    Used to test whether the configText: park222 configuration can be updated through the configuration center

  7. Manually refresh, call a post request, http://localhost:8800/actuator/refresh

  1. Send a get request again: http://localhost:8800/account/testConfig, you can see the configText has become park222, instructions manual refresh configuration file

Amqp refreshes the configuration

This configuration can refresh the configuration of all nodes of an entire service

  1. Install Erlang: www.erlang.org/downloads

    Download version 22.3, don’t download version 23.0

    After downloading the file, run it as an administrator. You are not advised to use the default installation path. After the installation is complete, you need to configure environment variables

After the environment variables are configured, enter ERL anywhere in CMD

  1. Install the RabbitMQ (under Windows) : www.rabbitmq.com/download.ht…

After the installation, go to its sbin directory, open CMD, enter two commands

Rabbitmqctl start_app install rabbitmq-plugins on RabbitMQ nodes to enable rabbitmq_managementCopy the code

Then double-click rabbitmq-server.bat in the sbin directory

Then open http://localhost:15672/ with the username and password guest

  1. Config Server and Consumer add dependencies

    org.springframework.cloud spring-cloud-starter-bus-amqp

  2. The current configuration of the config server is to add RabbitMQ

    Server: port: 5900Spring: application: name: config-server cloud: config: server: # Github.com/blppz/confi… Git branch label: master rabbitmq: host: localhost port: 5672 username: guest password: guesteureka: client: service-url: defaultZone: http://localhost:7900/eureka/

  3. Consumer bootstrap.properties is currently

    # configuration center spring. Cloud. Config. Uri = http://localhost:5900#git branch spring. Cloud. Config. The label = master# below two configuration, equivalent to enable the configuration file: Application – test. Yml, Spring. Cloud. Config. name=consumer#profile Part of the spring. Cloud. Config. Profile = dev# exposed all endpoints management endpoints. Web. Exposure. Include = * spring in the rabbitmq. Host = localhostspring. rabbitmq.port=5672spring.rabbitmq.username=guestspring.rabbitmq.password=guest

  4. Restart the two services.

    A. glancing at the current in the git configText park111, GET request: http://localhost:8800/account/testConfig

    B. then change in git configText park222, request it again: http://localhost:8800/account/testConfig, found that hasn’t changed

    C. POST request: http://localhost:8800/actuator/bus-refresh, and then call testConfig

Webhooks configure automatic refresh

It is generally not recommended to use automatic refresh, because it is difficult to ensure that the modified configuration file is correct. If configuration is necessary, refresh the configuration file on a single machine first and then automatically refresh the configuration file in batches

  1. Open the Git repository in the configuration center and add a Webhooks

  1. Payload URL Specifies the address that Git can access. If it is an Intranet, the company’s GitLab warehouse can access it

http://host:port/actuator/refresh

or

http://host:port/actuator/bus-refresh

  1. If Secret is specified, type encrypt.key in the configuration file