网络上关于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服务注册与发现的机制,继续学习实践中。