SpringCloud之Eureka:集群搭建

上篇文章《SpringCloud之Eureka:服务发布与调用例子》实现了一个简单例子,这次对其进行改造,运行两个服务器实例、两个服务提供者实例,服务调用者请求服务,使其可以进行集群部署。

集群结构如下图所示。

由于开发环境只有一台电脑,要构建集群,需要修改hosts文件,在里面添加主机名映射。

127.0.0.1 slave1 slave2

一、服务器端

1、创建项目

开发工具:IntelliJ IDEA 2019.2.2
IDEA中创建一个新的SpringBoot项目,名称为“first-cloud-server”,SpringBoot版本选择2.1.9,在选择Dependencies(依赖)的界面勾选Spring Cloud Discovert ->

Eureka Server,创建完成后的pom.xml配置文件自动添加SpringCloud最新稳定版本依赖,当前为Greenwich.SR3。
pom.xml完整内容可参考上篇文章《SpringCloud之Eureka:服务发布与调用例子》。

2、修改配置application.yml

由于需要对同一个应用程序启动两次,因此需要使用profiles配置。
下面配置了两个profiles,名称分别为slave1和slave2,当使用slave1启动服务器后,会向http://slave2:8762/eureka/注册自己,当使用slave2启动服务器后,会向

http://slave1:8761/eureka/注册自己,即两个服务器启动后,互相注册。

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、修改启动类代码FirstEkServerApplication.java

除了增加注解@EnableEurekaServer,还让类在启动时读取控制台输入,决定使用哪个profiles来启动服务器。

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);
    }

}

二、编写服务提供者

1、创建项目

IDEA中创建一个新的SpringBoot项目,除了名称为“first-cloud-provider”,其它步骤和上面创建服务器端一样。

2、修改配置application.yml

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

3、添加类 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、添加控制器 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、修改启动类代码FirstCloudProviderApplication.java

除了增加注解@EnableEurekaClient,还让类在启动时读取控制台输入,决定使用哪个端口启动服务器。

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);
    }

}

三、编写服务调用者

1、创建项目
IDEA中创建一个新的SpringBoot项目,除了名称为“first-cloud-invoker”,其它步骤和上面创建服务器端一样。

2、修改配置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、添加控制器 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(){
        RestTemplate restTpl = getRestTemplate();
        //根据应用名称调用服务
        String json = restTpl.getForObject("http://first-cloud-provider/user/1", String.class);
        return json;
    }
}

4、修改启动类代码FirstCloudInvokerApplication.java

添加注解@EnableDiscoveryClient,使得服务调用者可以去Eureka中发现服务。

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);
    }

}

四、编写REST客户端进行测试

1、创建项目

IDEA中创建一个新的SpringBoot项目,名称为“first-cloud-rest-client”,SpringBoot版本选择2.1.9,在选择Dependencies(依赖)的界面勾选Web->Spring Web。
在pom.xml中增加httpclient依赖。

<?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>

2、修改配置application.yml

server:
  port: 9001

3、修改启动类代码FirstCloudRestClientApplication.java

编写调用REST服务的代码

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、测试

(1)启动两个服务器端,在控制台中分别输入slave1和slave2启动。
(2)启动两个服务提供者,在控制台中分别输入8763和8764启动。
(3)启动服务调用者。
(4)启动REST客户端。

浏览器访问 http://slave1:8761/,页面如下

浏览器访问 http://slave2:8762/,页面如下

浏览器访问 http://localhost:8763/user/1,页面输出:

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

浏览器访问 http://localhost:8764/user/1,页面输出:

{"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次,可见已经达到负载均衡。

原文地址:https://www.cnblogs.com/gdjlc/p/11788591.html

时间: 2024-08-30 12:52:58

SpringCloud之Eureka:集群搭建的相关文章

Eureka集群搭建

Eureka集群搭建 高可用集群配置 当注册中心扛不住高并发的时候,这时候 要用集群来扛: 提示:部分内容请前往上篇博客查找 普通操作 我们再新建两个module  microservice-eureka-server-2002  microservice-eureka-server-2003 1.pom.xml 把依赖加下: microservice-eureka-server-2002 1 <?xml version="1.0" encoding="UTF-8&qu

Spring-Cloud学习之Eureka集群搭建

一.为什么需要集群 上一篇文章讲解了如何搭建单个节点的eureka,这篇讲解如何搭建eureka集群,这里的集群还是本地不同的端口执行三个eureka,因为条件不要允许,没有三台电脑,所以大家将就一下吧,eureka集群的目的就是防止一个点故障导致,整个服务瘫痪的问题,成为单点故障,因为一个点出问题,还有另一个点顶上去,代替这个点工作,所以集群也实现了高可用.高性能 二.集群的原理 每一个注册点都配置有其它点的url,能够与其他server点进行数据的同步,当服务向一个点注册时,该店就会把该服务

SpringCloud之Eureka集群

前面我们介绍了SpringCloud注册中心Eureka,但是存在一个单点故障的问题,一个注册中心远远不能满足实际的生产环境,现在我们介绍一下如何搭建一个Eureka集群. 一:集群环境搭建 我们先建两个注册中心工程,一个叫eureka_register_master,一个叫eureka_register_salve.master的端口是7998,salve的端口是7999. eureka_register_master的配置文件application.properties如下: server.

微服务架构:Eureka集群搭建

版权声明:本文为博主原创文章,转载请注明出处,欢迎交流学习! 服务注册.发现是微服务架构的关键原理之一,由于微服务架构是由一系列职责单一的细粒度服务构成的网状结构,服务之间通过轻量机制进行通信,这就必然引入一个服务注册发现的问题,也就是说服务提供方要注册报告服务地址,服务调用方要能发现目标服务.在我们的微服务架构中我们采用了Eureka来完成微服务的注册与发现.微服务通过Eureka进行注册,服务调用方通过Eureka找到目标服务.由于服务提供方以集群方式提供服务,Eureka也采用集群的方式来

springcloud中eureka集群unavailable-replicas

unavailable-replicas 配置了集群,但是在注册中心显示另外的几个集群地址是不可用的: 1 首先需要再host中添加服务名映射,如果应映射了再看是否在yml中配置了prefer-ip-address这个注解,如果配置了去掉集群地址就可用了: 2  下面这两个配置要么注释掉,要么设置 为true即可 fetch-registry: true # 获取注册信息register-with-eureka: true #注册信息到eureka 原文地址:https://www.cnblog

Spring Cloud Eureka集群搭建与注册

参考博文: 单元测试:https://blog.csdn.net/sz85850597/article/details/80427408 Eureka注册与发现:https://blog.csdn.net/qq_32529383/article/details/79951511 原文地址:https://www.cnblogs.com/free-wings/p/9687529.html

Eureka集群

Eureka集群搭建 高可用集群配置 当注册中心扛不住高并发的时候,这时候 要用集群来扛: 普通操作 新建两个stringboot项目 module  microservice-eureka-server-2002    microservice-eureka-server-2003 配置 microservice-eureka-server-2002 microservice-eureka-server-2003 pom.xml 依赖: 1 <?xml version="1.0"

基于dns搭建eureka集群

eureka集群方案: 1.通常我们部署的eureka节点多于两个,根据实际需求,只需要将相邻节点进行相互注册(eureka节点形成环状),就达到了高可用性集群,任何一个eureka节点挂掉不会受到影响. 2.可能会有初学者和我一样,一开始的时候没有完全理解eureka集群的原理,直接把每个eureka节点的url写进配置文件,期望所有的eureka节点进行相互注册.实际上,节点间进行信息同步的时候,只会选取配置文件第一个eureka的url,除非发生url错误,才会依次选取有效url进行信息同

springcloud费话之Eureka集群

  目录: springcloud费话之Eureka基础 springcloud费话之Eureka集群 springcloud费话之Eureka服务访问(restTemplate) springcloud费话之Eureka接口调用(feign) springcloud费话之断路器(hystrix in feign) 一.容灾server集群 复制上例中的server项目两个,分别命名为x-server2和x-server3,修改yml配置 ①端口:三个服务器的端口分别为9010,9011,901

eureka集群高可用配置

譬如eureka.client.register-with-eureka和fetch-registry是否要配置,配不配区别在哪里:eureka的客户端添加service-url时,是不是需要把所有的eureka的server地址都写上,还是只需要写一个server就可以了(因为server之间已经相互注册了)?如果写上了所有的server地址,那相当于将每个client服务都往所有的server都添加了一遍,那还配置server间的相互注册有什么意义? 上面的这些问题在多数讲eureka集群教