新人一看就懂:Spring Cloud Eureka服务注册发现的框架demo

x33g5p2x  于2021-12-30 转载在 Spring  
字(10.9k)|赞(0)|评价(0)|浏览(238)

这是一个基于Spring Cloud Eureka服务注册发现的框架demo,希望读者可以通过这篇文章大概能看懂这一个简单的框架搭建。后续我会陆续更新,微服务架构(Spring Boot、Spring Cloud)、分布式架构(Dobbo+Zookeeper)以及源码解析等相关的文章,感兴趣的话可以关注一下。

一、Eureka简介

Eureka是由Netflix开发的一款服务治理开源框架,Spring-cloud对其进行了集成。
  Eureka包含两个组件:Eureka Server和Eureka Client。
  Eureka服务端是一个服务注册中心(Eureka Server),提供服务的注册和发现,即当前有哪些服务注册进来可供使用;各个节点启动后,会在Eureka Server中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。
  Eureka客户端为服务提供者(Server Provider),t是一个java客户端,用于简化与Eureka Server的交互,客户端同时也就是一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,它将自己提供的服务注册到Eureka服务端,并周期性地发送心跳来更新它的服务租约,同时也能从服务端查询当前注册的服务信息并把它们缓存到本地并周期性地刷新服务状态。这样服务消费者(Server Consumer)便可以从服务注册中心获取服务名称,并消费服务。

二、eureka-server(服务注册中心)

1、pom.xml
  POM是项目对象模型(Project Object Model)的简称,它是Maven项目中的文件,使用XML表示,名称叫做pom.xml。作用类似ant的build.xml文件,功能更强大。该文件用于管理:源代码、配置文件、开发者的信息和角色、问题追踪系统、组织信息、项目授权、项目的url、项目的依赖关系等等。

<?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>
	<groupId>com.cloud</groupId>
	<artifactId>eureka-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>eureka-server</name>
	<description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> 
    </parent>

	<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

    <dependencyManagement>
        <!-- Spring Cloud版本 -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <!-- 引入服务注册发现组件 eureka依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

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

</project>

2、application.yml
  Spring Boot配置文件有两种:application.yml和application.properties,作用是一样的,不过因为yml文件是树状结构,写起来有更好的层次感,更易于理解,所以很多人都选择了yml文件。

spring:
  application:
    name: eureka-server

server:
  port: 8001

eureka:
  instance:
    hostname: localhost
  client:
    fetch-registry: false #是否注册自身 默认true-注册
    register-with-eureka: false #是否检查服务清单 默认true-检查
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

3、EurekaServerApplication
  在启动类上添加@EnableEurekaServer注解,表明这是一个Eureka服务端。

@SpringBootApplication
@EnableEurekaServer //启用服务注册服务
public class EurekaServerApplication {

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

}

启动服务,访问http://localhost:8001/,由于还没有Eureka客户端将服务注册进来,所以Eureka列表是空的。**

三、eureka-provider(服务提供者)

1、pom.xml
  和eureka-server的依赖基本相同,只有一处换成spring-cloud-starter-netflix-eureka-client。

<?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>
    <groupId>com.cloud</groupId>
    <artifactId>eureka-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-provider</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <!-- Spring Cloud版本 -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <!-- 引入服务注册发现组件 eureka依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

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

</project>

2、application.yml

spring:
  application:
    name: eureka-provider

server:
  port: 8002
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka/ #服务注册中心的Url

3、HelloController
  编写HelloController,对外提供一些REST服务。

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(String name) {
        return name + ", Welcome to Spring Cloud Eureka";

    }
}

4、EurekaProviderApplication
  在启动类上添加@EnableDiscoveryClient 注解,表明这是一个Eureka客户端。

@SpringBootApplication
@EnableDiscoveryClient //启用服务注册与发现
public class EurekaProviderApplication {

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

}

5、EnableDiscoveryClient与EnableEurekaClient的区别

  • @EnableDiscoveryClient注解是基于spring-cloud-commons依赖,并且在classpath中实现。
  • @EnableEurekaClient注解是基于spring-cloud-netflix依赖,只能为eureka作用。
  • @EnableEurekaClient只适用于Eureka作为注册中心,@EnableDiscoveryClient 可以是其他注册中心。

相同点:都用于SpringCloud的服务发现功能。
官方建议使用EnableDiscoveryClient

四、eureka-consumer(服务消费者)

1、pom.xml
  和eureka-provider的依赖基本相同。

<?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>
    <groupId>com.cloud</groupId>
    <artifactId>eureka-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/>
    </parent>

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

    <dependencyManagement>
        <!-- Spring Cloud版本 -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <!-- 引入服务注册发现组件 eureka依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

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

</project>

2、application.yml

spring:
  application:
    name: eureka-consumer

server:
  port: 8003
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka/ #服务注册中心的Url

3、EurekaConsumerApplication
  在启动类上加@EnableDiscoveryClient注解,表明这是一个Eureka客户端。

@SpringBootApplication
@EnableDiscoveryClient //启用服务注册与发现
public class EurekaConsumerApplication {

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

}

4、TestController

@RestController
public class TestController {
    @Autowired
    RestTemplate restTemplate;

    @LoadBalanced
    @Bean
    public RestTemplate rest() {
        return new RestTemplate();
    }

    @RequestMapping("/testHello")
    public String hello(String name) {
        return restTemplate.getForObject("http://eureka-provider/hello?name=" + name, String.class);
    }
}

5、RestTemplate和 @LoadBalanced
  使用了RestTemplate并且开启了客户端负载均衡功能,开启负载均衡很简单,只需要在RestTemplate的bean上再添加一个@LoadBalanced注解即可。

五、项目演示

1、先启动服务注册中心(eureka-server),以提供服务的注册。

2、再启动服务提供者(eureka-provider),将服务注册到服务注册中心,以便服务消费者进行调用。

启动成功后,我们也可以从控制台中看到注册成功的消息。

Registered Applications size is zero : true
Application version is -1: true
Getting all instance registry info from the eureka server
The response status is 200
Starting heartbeat executor: renew interval is: 30
InstanceInfoReplicator onDemand update allowed rate per min is 4
Discovery Client initialized at timestamp 1577329890774 with initial instances count: 0
Registering application EUREKA-PROVIDER with eureka with status UP
Saw local status change event StatusChangeEvent [timestamp=1577329890780, current=UP, previous=STARTING]
 DiscoveryClient_EUREKA-PROVIDER/localhost:eureka-provider:8002: registering service...
Tomcat started on port(s): 8002 (http) with context path ''
Updating port to 8002
Started EurekaProviderApplication in 6.562 seconds (JVM running for 7.765)

服务注册中心的注册信息:

3、最后启动服务消费者(eureka-consumer),消费其服务注册中心的服务。

4、服务全部启动成功。

5、服务消费者发送请求,调用服务提供者在服务注册中心的注册服务。

到此,调用服务通了!感兴趣的话可以去学习下。
想要demo源码的可以留下邮箱地址。

相关文章