SpringCloud:服务注册与发现

网络上关于Spring、Spring Boot、Spring Cloud是什么的文章非常多,基本就是一个简化开发者劳动而引申出框架的更新,详细请看《Spring Cloud体系介绍》 《各个组件的介绍》

使用SpringCloud搭建微服务,Eureka作为注册中心

1.新建SpringBoot项目

new—Project—Spring Initializr

这里写图片描述

Cloud Discovery—Eureka Server

这里写图片描述

2.服务端

配置文件application.yml设置

spring:
  application:
    name: server
server.port: 8761
eureka:
  client:
    register-with-eureka: false  #是否向服务注册中心注册自己
    fetch-registry: false  #是否检索服务
    service-url:
      defaultZone: http://localhost:8761/eureka/

服务端启动项注解:@EnableEurekaServer

3.客户端

配置文件application.yml设置

server:
  port: 8091
spring:
  application:
    name: consumer            #配置项目名
  cloud.client.ipAddress: 127.0.0.1  #配置Eureka中显示名称
eureka:
  client:             #配置要访问的注册中心地址,即eureka所在的地址
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:           #配置是否显示ip
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
    lease-renewal-interval-in-seconds: 1 #每间隔1s,向服务端发送一次心跳,证明自己依然”存活“
    lease-expiration-duration-in-seconds: 2 #告诉服务端,如果我2s之内没有给你发心跳,就代表我“死”了,将我踢出掉

客户端启动项注解:@EnableEurekaClient

Controller中

@Autowired
DiscoveryClient discoveryClient;//让服务发现服务器

@RequestMapping("/consumer5")
public String dc5(){
  String services = "Services: " + discoveryClient.getServices();//日志中打印出服务实例的相关内容
  return services;
}

4.访问效果

启动服务端和客户端,访问服务端接口如下:

这里写图片描述

访问客户端/consumer5,则获取到注册中心所有的服务

这里写图片描述

这是最基础的SpringCloud服务注册与发现的机制,继续学习实践中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值