首页 > 技术文章 > Spring生态系列文章 >

SpringCloud极简入门(四)高可用的Eureka Server集群

更新时间:2018-06-02 | 阅读量(1,065)

>作者:陈刚,叩丁狼高级讲师。原创文章,转载请注明出处。 ###一.什么是高可用Eureka Server集群 >在实际开发中,微服务实例可能有几十上百个之多,由于Eureka Server需要承担服务的注册任务,当服务数量一多,Eureka Server就需要承担非常高的负载,在SpringCloud中我们可以实现Eureka Server的高可用集群来减小负载,简而言之就是多创建几个Eureka Server程序相互注册来分担注册中心的压力。图例: ![image.png](https://upload-images.jianshu.io/upload_images/11046204-cee08d770e0601d4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ###二.项目改造 我们已经有一个Eureka Service应用,在这里我们把该应用进行改造,使用 多profile 的格式配置成两个Eureka Service环境 >1.修改原本的application.yml配置文件,重命名为 application-peer1.yml,并修改内容如下: ``` spring: profiles: peer1 #指定环境为 peer1 server: port: 1111 #注册中心 服务端口号为 1111 eureka: instance: hostname: peer1 #主机名 client: serviceUrl: defaultZone: http://peer2:1112/eureka/ #指向注册中心 peer2 的服务地址 ``` >2.再创建一个配置文件:application-peer2.yml,内容如下: ``` spring: profiles: peer2 #指定环境为 peer2 server: port: 1112 #注册中心 服务端口号为 1112 eureka: instance: hostname: peer2 #主机名 client: serviceUrl: defaultZone: http://peer1:1111/eureka/ #指向注册中心 peer1 的服务地址 ``` 在我们的配置文件中去掉了配置项:client.registerWithEureka 和 client.fetchRegistry ,因为我们需要实现注册中心之间的相互注册实现到高可用。并且我们定义了两个profile : peer1的hostname为 peer1,而peer2的hostname也是peer2,在实际开发中hostname应该配置为具体的服务IP,由于我们这里搭建的是本地Eureka Server集群,对于主机名:peer1和peer2我们需要在 hosts文件中去配置主机名。 >3.配置主机名:window系修改:c:/window/systems/drivers/etc/hosts 文件,mac系统通过vim/etc/hosts 修改,添加内容如下: ``` #本地ip地址 主机名 127.0.0.1 peer1 127.0.0.1 peer2 ``` >4.打包EurekaServer应用 :运行package进行打包 ![](https://upload-images.jianshu.io/upload_images/11046204-1c850f35b950ae00.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) >5.启动EurekaServer应用: 执行package打包后,在字节码输出目录会有打包好的应用jar包, ![image.png](https://upload-images.jianshu.io/upload_images/11046204-4cf03d4e617d637d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 找到其所在路径分别使用如下命令启动两次项目: ``` #使用 配置环境(profile) pee1启动注册中心服务 java -jar eureka-server-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1 #使用 配置环境(profile) pee2启动注册中心服务 java -jar eureka-server-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2 ``` >6.启动一个Eureka Client项目 :Producer 并访问 :http://localhost:1111/ 你会发现 Producer服务向 peer1节点的注册中心进行注册了,并且你还可以看到在Ds Replicas中显示了节点peer2,如图: ![](https://upload-images.jianshu.io/upload_images/11046204-c7c0f6c21b1b300d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 访问:http://localhost:1112/ 你会发现 Producer 服务也在 peer2节点的注册中心进行注册了,而我们的Producer应用的配置文件中的注册中心地址并没有指向 peer2,并且你可以在 DS Replicas中看到peer1 ,那说明我们的高可用集群成功,如图: ![image.png](https://upload-images.jianshu.io/upload_images/11046204-49c3f2ae8a74ea04.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![WechatIMG7.jpeg](https://upload-images.jianshu.io/upload_images/807144-66d6824f5ca71736.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
叩丁狼学员采访 叩丁狼学员采访
叩丁狼头条 叩丁狼头条
叩丁狼在线课程 叩丁狼在线课程