为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Cloud 微服务(三) 服务发现Eureka

标签:
Spring Cloud

我们创建了一个简单的服务,现在我们想治理我们的服务,首先需要做的是把服务注册在一个公共的服务上,让它可以被别的服务发现,本篇主要介绍Eureka服务发现。

项目搭建

我们还是像上一篇一样用IntelliJ的Spring Initializer创建一个基础工程,这次选择的组件是Eureka Server。

webp

image.png


这样我们就有了一个入口方法类以及一个配置文件。

webp

image.png


注意这里配置文件本来是application.properties,我改成了个人更喜欢的application.yml格式,这样可以用yaml格式来写配置,好处是比properties文件更能展示配置的层级关系。

服务注册与发现

打开入口文件,我们需要把这个服务注解成Eureka注册服务器,所以加上注解@EnableEurekaServer。

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

我们还需要配置一下服务器的端口,所以编辑application.yml:

server:
  port: 8081

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

我们配置了服务器的端口为localhost的8081,通过配置registerWithEureka false和fetchRegistry fase表明这是一个Eureka服务器。
这时启动项目,我们可以打开http://localhost:8081/ 观察Eureka服务器页面。


webp

image.png


看到Instances currently registered with Eureka,目前还没有服务注册。我们打开上一篇文章创建的项目,准备把它注册到我们的Eureka服务器作为一个Eureka Client。打开Client项目的配置文件修改:


server:
  port: 8870
spring:
  application:
    name: dummy-service
eureka:
  instance:
      hostname: localhost
      port: 8081
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${eureka.instance.port}/eureka/

Client端口监听8870,定义了一个名字叫"dummy-service"来作为服务名称,然后指定我们的Eureka Server为localhost:8081。然后在代码加上@EnableDiscoveryClient注解:

@EnableDiscoveryClient@RestController@SpringBootApplicationpublic class Example {    @RequestMapping("/")    String home() {        return “Hello World”;
    }
    ...
}
运行Client

启动我们的Client项目,它会自动去寻找我们的Eureka Server,并注册,这时候再刷新我们的http://localhost:8081/ 页面,就可以看到我们的服务"dummy-service"已经成功注册

webp

image.png


Client会发送心跳,CPU等运行数据给Eureka Server,所以如果Client挂了很快就会从Eureka Server上消失。



作者:Lin_XJ
链接:https://www.jianshu.com/p/67b0d2108f67


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消