1、搭建注册中心集群
删除application.properties文件,添加application-note1.yml,application-note2.yml,application-note3.yml文件
配置内容
application-note1.yml文件中 server: port: 8001 spring: application: name: eureka-server eureka: instance: hostname: note1 client: fetch-registry: true #检索eureka服务 register-with-eureka: true #注册自己到eureka服务中 service-url: defaultZone: http://note2:8002/eureka,http://note3:8003/eureka #map类型,多个逗号分开,指向 note2,note3
application-note2.yml文件中
server: port: 8002 spring: application: name: eureka-server eureka: instance: hostname: note2 client: fetch-registry: true #检索eureka服务 register-with-eureka: true #注册自己到eureka服务中 service-url: defaultZone: http://note1:8001/eureka,http://note3:8003/eureka #map类型,多个逗号分开,指向 note1,note3
application-note3.yml文件中
server: port: 8003 spring: application: name: eureka-server eureka: instance: hostname: note3 client: fetch-registry: true #检索eureka服务 register-with-eureka: true #注册自己到eureka服务中 service-url: defaultZone: http://note1:8001/eureka,http://note2:8002/eureka #map类型,多个逗号分开,指向 note2,note3
启动类添加注解@EnableEurekaServer,说明这是一个eureka注册服务
在pom.xml中添加maven打包插件将项目打包成jar文件eureka-server-cluster-0.0.1-SNAPSHOT.jar
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin>
Linux系统在/etc/hosts文件末尾添加对note1、note2、note3的转换,windows系统位置C:\Windows\System32\drivers\etc\hosts
127.0.0.1 note1
127.0.0.1 note2
127.0.0.1 note3
将打包成的eureka-server-cluster-0.0.1-SNAPSHOT.jar 分别以note1,note2,note3运行
java -jar E:\ideaWorkspace\eureka-server-cluster\target\eureka-server-cluster-0.0.1-SNAPSHOT.jar --spring.profiles.active=note1
java -jar E:\ideaWorkspace\eureka-server-cluster\target\eureka-server-cluster-0.0.1-SNAPSHOT.jar --spring.profiles.active=note2
java -jar E:\ideaWorkspace\eureka-server-cluster\target\eureka-server-cluster-0.0.1-SNAPSHOT.jar --spring.profiles.active=note3
这个时候注册中心集群已经搭成,浏览器中输入http://localhost:8001/,http://localhost:8002/,http://localhost:8003/,发现都有了另外的两个EUREKA-SERVER服务
这个时候你发现每一个注册中心有四个服务,8001,8002,8003,8004(eureka客户端,下面再说)
2、eureka客户端
创建方式与服务端略有不同
此处添加了两项,一项为Web,另一项Eureka Discovery Client
application.yml配置文件内容
spring: application: name: eureka-client eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://note1:8001/eureka,http://note2:8002/eureka,http://note3:8003/eureka #指定服务注册中心的位置,多个逗号分隔 server: port: 8004
启动类添加@EnableEurekaClient
编写REST API提供服务
由于我写的Controller不在启动类所在的包以及子包下面,所有要在启动类上添加另外一个注解@ComponentScan(basePackages = {"com.tjf"})来告知扫描的基包。
启动客户端,浏览器中输入http://localhost:8004/client/index?name=“eureka client“
此时刷新上面的集群地址http://localhost:8001/,http://localhost:8002/,http://localhost:8003/,就会发现上面多出的8004服务
集群的好处就是如果其中有几个注册中心服务挂掉了,只要有一个就可以对外提供服务,比如8003这个服务挂了,你会在另外两个服务中中心的unavailable-replicas中看见8003的存在