Spring Cloud中的Eureka服务注册

Eureka服务注册的简单步骤

Eureka是Spring Cloud中的服务注册中心,以下是Eureka服务注册的简单步骤:

  1. 启动Eureka服务注册中心;
  2. 将需要注册的服务注册到Eureka;
  3. 其他服务从Eureka获取服务列表,根据需要调用需要注册的服务。

搭建Eureka服务注册中心

创建子工程模块eureka_server

添加依赖

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

项目配置文件:application.yml

spring:
  application:
    name: eureka-server
server:
  port: 9000
eureka:
  instance:
    hostname: localhost
  client:
    #是否将自己注册到注册中心
    registerWithEureka: false
    #是否从eureka中获取注册信息
    fetchRegistry: false
    #配置暴露给Eureka Client的请求地址
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    #关闭自我保护
    enable-self-preservation: false
    #剔除服务间隔的时间
    eviction-interval-timer-in-ms: 4000

启动类中添加 @EnableEurekaServer 注解

@SpringBootApplication
// 激活eurekaserver
@EnableEurekaServer
public class EurekaServerApplication {

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

}

启动类

在浏览器输入http://localhost:9000/​​​​​​

能看到如下界面,说明eureka注册中心服务搭建成功 

把服务注册到注册中心

把各个微服务注册到注册中心步骤如下:

1.添加EurekaClient依赖

2.服务注册:修改application.yml添加EurekaServer的信息

3.修改启动类

创建product-serviceI商品服务注册到Eureka注册中心

 添加依赖

<!--eureka-client客户端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

项目配置文件:application.yml添加EurekaServer的信息

eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/

启动类中添加 @EnableEurekClient 注解

// 激活EurekaClient
@EnableEurekaClient
//product 产品
@SpringBootApplication
@EntityScan("com.example.productservice.entity")
public class ProductServiceApplication {

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

}

启动eureka服务和product服务

可以看出,已经有个微服务注册进来了,名字为:SERVICE-PRODUCT。这个名字从哪来的呢?配置文件里面指定了暴露的服务名称,只不过 Eureka 里默认全部大写而已。也可以看出,该服务的端口是9001。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值