1 Zookeeper service registration and discovery
1. Introduction

effect
(1) Zookeeper is a distributed coordination tool, which can realize the function of registry.
(2) Turn off the firewall of the Linux server and start the Zookeeper server.
(3) Zookeeper server replaces Eureka server, and zookeeper acts as the registration center.
2. Service provider cloud provider payment8004
1. Create project
1. Project structure

2. Add yml file
#8004 indicates the port number of the payment service provider registered with the zookeeper server server: port: 8004 #Service alias --- the name of the registry where zookeeper is registered #Use the following 39.96.161.64 address and open the port number to register the server spring: application: name: cloud-provider-payment cloud: zookeeper: connect-string: 39.96.161.64:2181
3. Main startup class
/** * @EnableDiscoveryClient * There is no need to add Eureka at this time * This annotation is used to register services when using consumer or zookeeper as the registry */ @SpringBootApplication @EnableDiscoveryClient public class PaymentMain8004 { public static void main(String[] args) { SpringApplication.run(PaymentMain8004.class, args); } }
4,Controller
@RestController @Slf4j public class PaymentController { @Value("${server.port}") private String serverPort; @GetMapping(value = "/payment/zk") public String paymentzk(){ return "springcloud with zookeeper:"+serverPort+"\t"+ UUID.randomUUID().toString(); } }
5. Start the zookeeper service on alicloud server
6. Start cloud provider payment8004 to register with zookeeper
(1) Problems encountered after startup

This is because the version of zookeeper used on our server is 3.4.10, while the version in the dependency imported in IDEA is 3.5.3, which leads to the conflict of zookeeper version jar package.

(2) Solution
<!-- Only this one is new. SpringBoot integration Zookeeper client jar Package conflict and error reporting, jar Exclusion and introduction of packages --> <!-- <dependency>--> <!-- <groupId>org.springframework.cloud</groupId>--> <!-- <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>--> <!-- </dependency>--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <!--Exclude own first zk3.5.3--> <exclusions> <exclusion> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </exclusion> </exclusions> </dependency> <!--Add again zk 3.4.10 Version, with server zk agreement--> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.10</version> </dependency>
7. Testing
(1) Enter the following URL:
http://localhost:8004/payment/zk
A port and a serial number will be returned on the web page.
(2) After obtaining the json string, use the online tool to view it.
First, after starting the zookeeper server, start the client with the following instructions to view:
./zkCli.sh
Obtain the service node through the following instructions:
ls /
The cloud provider payment8004 node is a temporary node.
3. Service consumer cloud-consumerzk-order80
1. Create project
1. Project structure

2. Add yml file
server: port: 80 spring: application: name: cloud-consumer-order cloud: #Address registered in zookeeper zookeeper: connect-string: 39.96.161.64:2181
3. Startup class
@SpringBootApplication @EnableDiscoveryClient public class OrderZKMain80 { public static void main(String[] args) { SpringApplication.run(OrderZKMain80.class,args); } }
4. Business class
(1) Configure Bean
@Configuration public class ApplicationContextConfig { @LoadBalanced @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
(2)controller
@RestController @Slf4j public class OrderZKController { public static final String INVOME_URL = "http://cloud-provider-payment"; @Resource private RestTemplate restTemplate; @GetMapping("/consumer/payment/zk") public String payment (){ String result = restTemplate.getForObject(INVOME_URL+"/payment/zk",String.class); return result; } }
5. Start cloud-consumerzk-order80 to register with zookeeper
6. Testing
At this time, cloud provider payment8004 and cloud consumer ZK order80 run simultaneously in the environment.
(1) View the zoomeeper node of alicloud server

(2) Enter web address:
http://localhost:8004/payment/zk
A port and a serial number will be returned on the web page.

(3) Enter web address:
http://localhost/consumer/payment/zk

2 Consul service registration and discovery
1. Introduction
1. Web address
Introduction website:
https://www.consul.io/intro/index.html
Download website:
https://www.consul.io/downloads.html

2. Function
(1) Service discovery: provides two discovery methods: HTTP and DNS.
(2) Health monitoring: support a variety of protocols, including HTTP, TCP, Docker and Shell script customization.
(3) KV storage: the storage method of key and value.
(4) Multiple data centers: Consul supports multiple data centers.
(5) Visual Web interface.
2. Install and run Consul
1. After downloading, there is only one consumer Exe file, double-click to run under the hard disk path, and use the following instructions to view the version information.
consul --version

2. Start using development mode
(1) Start consumer with the following command:
consul agent -dev
(2) Consul t's home page can be accessed at the following address:
http://localhost:8500
(3) Results page

3. Service provider cloud providerconsumer payment8006
1. Create project
1. Project structure

2. Add yml file
#Consumer service port number server: port: 8006 spring: application: name: consul-provider-payment #Address of consumer Registration Center cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name}
3. Main startup class
@SpringBootApplication @EnableDiscoveryClient public class PaymentMain8006 { public static void main(String[] args) { SpringApplication.run(PaymentMain8006.class,args); } }
4. Business class controller
@RestController @Slf4j public class PaymentController { @Value("${server.port}") private String serverPort; @GetMapping(value = "/payment/consul") public String paymentConsul() { return "springcloud with consul: " + serverPort + "\t" + UUID.randomUUID().toString(); } }
5. Testing
Enter web address:
http://localhost:8006/payment/consul
There will be a port number + a series of serial numbers; Enter web address:
http://localhost:8500
The following interface will pop up:

4. Service consumer cloud-consumerconsul-order80
1. Create project
1. Project structure

2. Add file yml
server: port: 80 spring: application: name: consul-consumer-order cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name}
3. Main startup class
@SpringBootApplication @EnableDiscoveryClient public class OrderConsulMain80 { public static void main(String[] args) { SpringApplication.run(OrderConsulMain80.class,args); } }
4. Business class
(1) Configure Bean
@Configuration public class ApplicationContextConfig { @LoadBalanced @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
(2)controller
@RestController @Slf4j public class OrderConsulController { public static final String INVOME_URL = "http://consul-provider-payment"; @Resource private RestTemplate restTemplate; @GetMapping("/consumer/payment/consul") public String payment() { String result = restTemplate.getForObject(INVOME_URL + "/payment/consul", String.class); return result; } }
5. Testing
(1) Enter web address:
http://localhost:8500
The following interface will pop up:

(2) Enter web address: http://localhost/consumer/payment/consul , will get
Port number of cloud provider consumer payment8006 + a series of serial numbers.
5. Similarities and differences of the three registries
1,CAP
(1) C: consistency
(2) A: availability
(3) P: partition tolerance
CAP theory focuses on granularity, which is data, not the strategy of overall system design.
2. Analysis


Component name | language | CAP | Server health check | External reserved interface | SpringBoot integration |
---|---|---|---|---|---|
Eureka | Java | AP | Configurable support | HTTP | Integrated |
Consul | Go | CP | support | HTTP/DNS | Integrated |
Zookeeper | Java | CP | support | client | Integrated |
(1)AP(Eureka)


(2)CP(Zookeeper/Consul)


3 Ribbon load balancing service call
1. Introduction

1. Official website information
website: https://github.com/Netflix/ribbon/wiki/Getting-Started
At present, Ribbon has also entered the maintenance stage:

Alternatives:

2. Function
(1) Load balancing

(a) Centralized LB

(b) Program LB

(2) Summary
Load balancing + RestTemplate call (80 accesses 8001 / 8002 through polling load).
2. Load balancing demo
1. Architecture description
Ribbon is actually a client component of soft load balancing. It can be used in combination with other clients that need requests. The combination with eureka is just one example.


2. pom file


3. Use of RestTemplate
(1) Official website
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

(2) getForObject method / getForEntity method

(3)postForObject/postForEntity

3. Ribbon core component IRule
1. Select a service to be accessed from the service list according to a specific algorithm.


2. How to replace
(1) Modify cloud-consumer-order80 module
Configuration details:


(2) New package-com.com xiaolun. myrule

(3) Add rule class
@Configuration public class MySelfRule { @Bean public IRule myRule(){ return new RandomRule();//Defined as random } }
(4) Add annotation @ RibbonClient to the main startup class
@EnableEurekaClient @SpringBootApplication @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class) public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class,args); } }
(5) Testing
Enter web address:
http://localhost/consumer/payment/get/5
Random access.
4. Handwriting load balancing algorithm
1. Principle

2. Handwriting algorithm
(1) Start cloud-eureka-Server-7001/7002.
(2) Transform cloud provider payment8001 / 8002
//Add the following content to the controller. When the consumer accesses, the port number can be returned @GetMapping(value = "/payment/lb") public String getPaymentLB() { return serverPort; }
(3) Transform cloud-consumer-order80
(a) ApplicationContextBean removes @ LoadBalanced and mainly uses its own load balancing.
(b) Create LoadBalancer interface

public interface LoadBalancer { //Collect the total number of servers that can provide services and put them in the list ServiceInstance instances(List<ServiceInstance> serviceInstances); }
(c) LoadBalancer interface implementation class
@Component public class MyLB implements LoadBalancer { private AtomicInteger atomicInteger = new AtomicInteger(0); //coordinate private final int getAndIncrement() { int current; int next; do { current = this.atomicInteger.get(); next = current >= 2147483647 ? 0 : current + 1; } while (!this.atomicInteger.compareAndSet(current, next)); //The first parameter is the expected value and the second parameter is the modified value System.out.println("*******Number of visits next: " + next); return next; } @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { //Get a list of machines int index = getAndIncrement() % serviceInstances.size(); //Get the subscript location of the server return serviceInstances.get(index); } }
(d) Transform controller
@Resource private LoadBalancer loadBalancer; @Resource private DiscoveryClient discoveryClient; @GetMapping(value = "/consumer/payment/lb") public String getPaymentLB() { List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"); if (instances == null || instances.size() <= 0) { return null; } ServiceInstance serviceInstance = loadBalancer.instances(instances); URI uri = serviceInstance.getUri(); log.info("uri-----"+uri); return restTemplate.getForObject(uri + "/payment/lb", String.class); }
(e) Testing
Enter web address:
http://localhost/consumer/payment/lb
Browser output:

Ports 8001 / 8002 can be changed alternately, that is, load balancing is realized.
5 OpenFeign service interface call
1. Introduction
1. Overview

Feign is a declarative web service client, which makes it very easy to write a web service client. You just need to create an interface and add annotations on the interface.
GitHub:
https://github.com/spring-cloud/spring-cloud-openfeign
2. Function

3. The difference between Feign and OpenFeign

2. OpenFeign usage steps
Core: interface + annotation: Micro service call interface + @ FeignClient.
Project structure:

1. Create a new cloud consumer feign order80. Feign is used on the consumer side.
2. Add pom file
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
3. Add yml file
server: port: 80 spring: application: name: cloud-order-service eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
4. Add main startup class
@SpringBootApplication @EnableFeignClients //Add this annotation @EnableEurekaClient public class OrderFeignMain80 { public static void main(String[] args) { SpringApplication.run(OrderFeignMain80.class, args); } }
5. Add business class
Implementation: business logic interface + @ FeignClient configuration calls provider service.
(1) Create a new PaymentFeignService interface and add the annotation @ FeignClient
@Component //The name of the CLOUD-PAYMENT-SERVICE service @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService { @GetMapping("/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id); }
The annotation @ FeignClient is a used identifier, and the annotation @ EnableFeignClients in the startup class is an enabled identifier.
(2) Add controller
@RestController public class OrderFeignController { @Resource private PaymentFeignService paymentFeignService; @GetMapping(value = "/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){ return paymentFeignService.getPaymentById(id); } }
5. Testing
First start two eureka clusters cloud eureka server7001 / 7002, then start two microservices cloud provider payment8001 / 8002, and finally start cloud consumer feign order80. Enter the address:
http://localhost/consumer/payment/get/5

It can be found that Feign has its own load balancing configuration item, and the port number 8001 / 8002 in the above figure switches back and forth.
Execution logic:
The cloud-consumer-feign-order80 module is now a consumer. When the client enters the address, the address will first enter the controller in the cloud-consumer-feign-order80 module, that is, the method of OrderFeignController. After execution, the method will execute the @ GetMapping method in the interface class PaymentFeignService, so that cloud provider payment8001 / 8002 can be called through OpenFeign, That is, the network between consumers and service providers is opened.

3. Timeout control
1. Case
(1) COM in cloud provider payment8001 / 8002 xiaolun. springcloud. Add delay program to controller:
@GetMapping(value = "/payment/feign/timeout") public String paymentFeignTimeout() { try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) { e.printStackTrace(); } return serverPort; }
(2) Service consumer cloud consumer feign order80 interface com xiaolun. service. Add a timeout method in PaymentFeignService (corresponding to the method in (1))
@GetMapping(value = "/payment/feign/timeout") public String paymentFeignTimeout();
(3) Control class of service consumer cloud-consumer-feign-order80 com xiaolun. controller. Add timeout method PaymentFeignService in orderfeigncontroller
@GetMapping(value = "/consumer/payment/feign/timeout") public String paymentFeignTimeout(){ return paymentFeignService.paymentFeignTimeout(); }
(4) Testing
First start two eureka clusters cloud eureka server7001 / 7002, then start two microservices cloud provider payment8001 / 8002, and finally start cloud consumer feign order80. Enter the address:
http://localhost/consumer/payment/feign/timeout
There will be the following error interface:

2. Solution of timeout problem

Therefore, we need to open the timeout configuration information in the yml file. Because OpenFeign supports Ribbon by default, as shown in the following figure:

We only need to add the following configuration in the yml file to enable the OpenFeign client timeout control:
#Set feign client timeout (OpenFeign supports ribbon by default) ribbon: #It refers to the time taken to read available resources from the server after the connection is established ReadTimeout: 5000 #It refers to the time taken to establish a connection, which is applicable to the connection time at both ends under normal network conditions ConnectTimeout: 5000
Note: when we only add the method in cloud provider payment8001, but not in cloud provider payment8002, because cloud consumer feign order80 will poll the access service provider, there will be an error in the process of access.
4. Log printing
1. Introduction

Log level:

2. Configuration of log printing
(1) Directory structure

(2) On COM xiaolun. Configure log bean under config
@Configuration public class FeignConfig { @Bean Logger.Level feignLoggerLevel(){ //A detailed log is opened on behalf of yourself return Logger.Level.FULL; } }
(3) Open the Feign client of the log in the yml file
logging: level: #feign logs monitor the following interface at the debug level and print out all log information com.xiaolun.service.PaymentFeignService: debug
(4) Background log viewing
