loading...
SpringCloud注册中心
Published in:2022-01-31 | category: SpringCloud
Words: 466 | Reading time: 2min | reading:

SpringCloud注册中心

实践步骤

1.开发eureka注册中心

  1. 创建web应用

  2. 添加eureka server 依赖

    1
    2
    3
    4
    5
    <!-- 1.eureka依赖-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
  3. 在启动类前添加@EnableEurekaServer注解

  4. 配置application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

server:
port: 8761 #端口号
# eureka注册中心实例
eureka:
instance:
hostname: localhost

client:
# 是否把eurekaserver作为服务注册
register-with-eureka: false
#是否抓取已注册服务
fetch-registry: false
# 提供给其他服务的注册及搜索地址
service-url:
defalutZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# serviceUrl:
# defalutZone: http://localhost:8761/eureka

2.开发eureka服务提供者

  1. 创建web应用

  2. 添加eureka客户端依赖

    1
    2
    3
    4
    5
    <!--        添加客户端依赖-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
  3. 在提供者的启动类前添加@EnableEurekaClient //开启eureka客户端注册功能

  4. 修改配置application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    eureka:
    client:
    service-url:
    # 配置服务注册中心地址
    defalutZone: http://localhost:8761/eureka

    # 指定服务的名称
    spring:
    application:
    #服务名 不得出现下划线及其他特殊字符,不区分大小写
    name: provider-service
    server:
    port: 9091
  5. 开发对外业务接口

3.开发eureka服务消费者

  1. 创建web应用

  2. 添加eureka客户端依赖

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
  3. 在提供者的启动类前添加@EnableEurekaClient或@EnableDiscoverClient

  4. 修改配置application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #3、
    server:
    port: 9092
    spring:
    application:
    # 消费者服务名称
    name: consumer-service
    # 配置注册中心地址
    eureka:
    client:
    service-url:
    defaultZone: http://localhost:8761/eureka
  5. 开发调用业务逻辑

    注意:

    • EurekaClient:eureka客户端包含的Java客户端访问对象,从eurekaservers中搜索服务

    • RestTemplate:可以使用Java程序访问远程Http或Https服务

    • 核心API:

      1
      2
      //参数1:
      restTemplate.getForObject(url,String.class);
Prev:
SSO单点登录
Next:
Spring 定时任务
catalog
catalog