springcloud(三)服务治理之服务提供者

一、概述

分布式系统架构中的所有微服务都需要在注册中心完成注册才能被发现进而使用,所谓的服务提供者和服务消费者是从业务角度来划分的,实际上服务提供者和服务消费者都是通过 Eureka Client 连接到 Eureka Server 完成注册。

二、搭建服务提供者

通过 Spring Boot 搭建一个微服务应用,再通过 Eureka Client 将其注册到 Eureka Server,创建 Eureka Client 的过程与创建 Eureka Server 十分相似。

1、在mysringcloud 工程下创建子module 实现 Eureka Client。工程目录如下图所示:

pom文件添加依赖:

<dependencies>
        <!--添加 Eureka Client 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

2、在 resources 路径下创建配置文件 application.yml,添加 Eureka Client 相关配置,此时的 Eureka Client 是服务提供者 provider。

server:
  port: 8011 #当前 Eureka Client 服务端口
spring:
  application:
    name: provider #当前服务注册在 Eureka Server 上的名称
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/ #注册中心的访问地址
  instance:
    prefer-ip-address: true #是否将当前服务的 IP 注册到 Eureka Server

3、java 路径下创建启动类 ProviderApplication。

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

4、依次启动注册中心,运行ProviderApplication。打开注册中心看到如下界面:

此时可以看到服务提供者 provider 已经在 Eureka Server 完成注册,接下来就可以访问 provider 提供的相关服务了。

本 demo 在 provider 服务中提供对 Student 的 CRUD 操作。demo下载地址:

https://gitee.com/zhengj/myspringcloud.git

发布了9 篇原创文章 · 获赞 0 · 访问量 347

猜你喜欢

转载自blog.csdn.net/m0_37874989/article/details/104427028