参考了尚硅谷的spring cloud课程,做了一些笔记,完整代码:https://github.com/yao09605/mscloud
文章目录
什么是Eureka?
微服务架构中服务调用关系比较复杂,所以启用一个服务注册中心,统一管理服务的注册。可以实现服务调用,服务发现和注册。
Eureka集群原理
几台机器互相注册,每个机器上都有所有服务的注册表
新建两个module作为Eureka服务器
cloud-eureka-server7001 cloud-eureka-server7002
两个module基本上是复制黏贴
Pom 添加如下依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
配置文件:main/resources/application.yml
server:
port: 7001 #另一个文件配成7002
eureka:
instance:
hostname: eureka7001.com #另一个文件配成eureka7002.com
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://eureka7002.com:7002/eureka/ #另一个文件配成http://eureka7001.com:7001/eureka/
修改hosts文件(本地模拟配置的话)
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
主启动类 添加:@EnableEurekaServer
package org.example.mscloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaMain7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7001.class, args);
}
}
将服务注册在Eureka上
在pom添加如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
yml增加配置
spring:
application:
name: cloud-payment-service #服务名
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url: #eureka服务器的地址
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
instance:
instance-id: payment8001 #服务显示的名字
prefer-ip-address: true #反馈服务的ip
主启动加上 @EnableEurekaClient
@EnableEurekaClient
@SpringBootApplication
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class,args);
}
}
调用方
pom添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
调用方不再直接调IP,而使用服务名:
public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";