SpringCloud of Eureka: Cluster Setup

The article " SpringCloud of Eureka: Services issued calling examples " to achieve a simple example, this time its transformation, run two server instances, two examples of service provider, serving the caller requests a service, it can be cluster deployment.

Cluster configuration as shown in FIG.

 Because the development environment is only one computer, to build a cluster, you need to modify the hosts file, add the hostname mapping inside.

127.0.0.1 slave1 slave2

 

A server-side

1. Create a project

Development Tools: IntelliJ IDEA 2019.2.2
create a new SpringBoot IDEA project, named "first-cloud-server", SpringBoot version 2.1.9 choice in the selection Dependencies (dependent) interface Cloud discovert check the Spring ->
Eureka Server, after the pom.xml configuration file is created automatically add SpringCloud latest stable version dependency, currently Greenwich.SR3.
pom.xml full content can refer to the article " SpringCloud of Eureka: Services issued calling example ."

2, modify the configuration application.yml

Due to the need to start twice for the same application, it is necessary to use profiles to configure.
Below is configured with two profiles, respectively slave1 name and slave2, when to start using slave1 server, the http: // slave2: 8762 / eureka / register yourself, when to start using slave2 server, the
http: // slave1 : 8761 / eureka / register itself, that is, after two server startup, registration with each other. 

server:
  port: 8761
spring:
  application:
    name: first-cloud-server
  profiles: slave1
eureka:
  instance:
    hostname: slave1
  client:
    ServiceUrl:
      defaultZone: http://slave2:8762/eureka/
---
server:
  port: 8762
spring:
  application:
    name: first-cloud-server
  profiles: slave2
eureka:
  instance:
    hostname: slave2
  client:
    ServiceUrl:
      defaultZone: http://slave1:8761/eureka/

3, the class code to modify the startup FirstEkServerApplication.java

In addition to adding annotations @EnableEurekaServer, but also to class to read console input when you start, decide which profiles to start the server. 

package com.example.firstcloudserver;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

import java.util.Scanner;

@SpringBootApplication
@EnableEurekaServer
public class FirstCloudServerApplication {

    public static void main(String[] args) {
        //SpringApplication.run(FirstCloudServerApplication.class, args);
        Scanner scan = new Scanner(System.in);
        String profiles = scan.nextLine();
        new SpringApplicationBuilder(FirstCloudServerApplication.class)
                .profiles(profiles).run(args);
    }

}

Second, the preparation of the service provider

1. Create a project

Create a new SpringBoot IDEA project, in addition to the name "first-cloud-provider", create server-side and other steps as above.

2, modify the configuration application.yml

spring:
  application:
    name: first-cloud-provider
eureka:
  instance:
    hostname: localhost
  client:
    ServiceUrl:
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

3, add the class User.java

package com.example.firstcloudprovider;

public class User {
    private Integer id;
    private String name;
    private String message;

    public User(Integer id, String name){
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

4, adding a controller UserController.java

package com.example.firstcloudprovider;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {
    @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public User findUser(@PathVariable("userId") Integer userId, HttpServletRequest request){
        User user = new User(userId, "gdjlc");
        user.setMessage(request.getRequestURL().toString());
        return user;
    }
}

5, start modifying the class code FirstCloudProviderApplication.java

In addition to adding annotations @EnableEurekaClient, but also to class to read console input when you start, decide which port to use to start the server. 

package com.example.firstcloudprovider;

//import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import java.util.Scanner;

@SpringBootApplication
@EnableEurekaClient
public class FirstCloudProviderApplication {

    public static void main(String[] args) {
        //SpringApplication.run(FirstCloudProviderApplication.class, args);
        Scanner scan = new Scanner(System.in);
        String port = scan.nextLine();
        new SpringApplicationBuilder(FirstCloudProviderApplication.class).properties("server.port=" + port).run(args);
    }

}

 

Third, the caller writing service

1. Create a project
IDEA SpringBoot create a new project, in addition to the name "first-cloud-invoker", create server-side and other steps as above.

2, modify the configuration application.yml

server:
  port: 9000
spring:
  application:
    name: first-cloud-invoker
eureka:
  instance:
    hostname: localhost
  client:
    ServiceUrl:
      defaultZone: http://slave1:8761/eureka/,http://slave2:8762/eureka/

3, adding a controller InvokerController.java

package com.example.firstcloudinvoker;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Configuration
public class InvokerController {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @RequestMapping(value = "/router", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String router(){
        RestTpl RestTemplate = getRestTemplate ();
         // Depending on the application calls the service name 
        String json = restTpl.getForObject ( "HTTP: // First-Cloud-Provider / the User / 1", String. Class );
         return json;
    }
}

4, to modify the startup class code FirstCloudInvokerApplication.java

Add annotations @EnableDiscoveryClient, making service calls can go to Eureka found service. 

package com.example.firstcloudinvoker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class FirstCloudInvokerApplication {

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

}

 

Fourth, write REST client testing

1. Create a project

IDEA to create a new SpringBoot project, named "first-cloud-rest-client ", SpringBoot select version 2.1.9, check Web-> Spring Web in select Dependencies (dependent) interface.
Httpclient dependent increase in pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>first-cloud-rest-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first-cloud-rest-client</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

2, modify the configuration application.yml

server:
  port: 9001

3, the class code to modify the startup FirstCloudRestClientApplication.java

 Write code to call REST services

package com.example.firstcloudrestclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class FirstCloudRestClientApplication {

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

    @RequestMapping("/")
    public String testHttpClient(){
        StringBuilder sb = new StringBuilder();
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            for(int i=0;i<10;i++){
                HttpGet httpGet = new HttpGet("http://localhost:9000/router");
                HttpResponse response = httpClient.execute(httpGet);
                sb.append(EntityUtils.toString(response.getEntity()) + "<br />");
            }
        }catch(Exception ex){
            return ex.getMessage();
        }
        return sb.toString();
    }
}

4, the test

(1) start the two server, in the console and the input, respectively slave1 slave2 start.
(2) starts two service providers in the console input, respectively, 8763 and 8764 start.
(3) to start the service the caller.
(4) Start REST client.

Browser to access http: // slave1: 8761 /, the following page

 

 Browser to access http: // slave2: 8762 /, the following page

 

 Browser to access http: // localhost: 8763 / user / 1, page output:

{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}

Browser to access http: // localhost: 8764 / user / 1, page output:

{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}

浏览器访问 http://localhost:9000/router,多次刷新页面,页面输出在8763和8764切换:

{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}

浏览器访问 http://localhost:9001/,页面输出 

{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8764/user/1"}
{"id":1,"name":"gdjlc","message":"http://localhost:8763/user/1"}

请求了10次,8763和8764分别被请求5次,可见已经达到负载均衡。

Guess you like

Origin www.cnblogs.com/gdjlc/p/11788591.html