Spring Cloud 服务治理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chq00788/article/details/77822639

Spring Cloud Eureka 是Spring Cloud Netflix 微服务套件中的一部分,它基于 Netflix Eureka 做了二次封装,主要负责完成微服务框架中的服务治理功能。

Spring Cloud 通过为Eureka 增加了 Spring Boot 风格的自动化配置,我们只需通过简单引入依赖和注解配置就能让Spring Boot 构建的微服务应用轻松地与Eureka服务治理体系进行整合。

服务治理是微服务架构中最为核心和基础的模块,它主要用来实现各个微服务实例的自动化注册与发现。

1、创建项目spring-cloud-discovery-eureka

使用IDEA创建一个spring boot 项目,项目集成spring-cloud-parent.
项目POM文件内容如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.chq.demo.spring-cloud</groupId>
    <artifactId>spring-cloud-discovery-eureka</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-cloud-discovery-eureka</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.chq.demo.spring-cloud</groupId>
        <artifactId>spring-cloud-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

2、使用注解@EnableEurekaServer申明一个注册中心

在Spring Boot 启动文件中加入注解@EnableEurekaServer,启动一个服务注册中心提供给其他程序进行对话。

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudDiscoveryEurekaApplication {

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

3、配置application.yml文件

在默认情况下,Eureka会将自己也作为客户端尝试注册,所以在单机模式下,我们需要禁止该行为,只需要在application.yml中如下配置:

server:
  port: 8001  # 指定该Eureka实例的端口
eureka:
  instance:
    hostname: discovery  # 指定该Eureka实例的主机名
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

4、启动程序

运行Spring Boot 启动文件,启动程序,然后访问:http://localhost:8001/ 可以看到服务管理界面:
这里写图片描述

现在并没有服务注册到Eureka中。

项目代码:https://github.com/chq00788/spring-cloud-discovery-eureka

猜你喜欢

转载自blog.csdn.net/chq00788/article/details/77822639