一、注册中心
1、新建maven项目eureka-server,引入对应jar包:
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
2、EnableEurekaServer注册Application
package com.tan.self;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* Author: Mr.tan
* Date: 2017/9/9
*/
@EnableEurekaServer // 开启服务注册服务
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3、application.properties配置
server.port= 1111
eureka.instance.hostname= localhost
# 不需要向注册中心注册自己
eureka.client.register-with-eureka=false
# 不需要去检索服务
eureka.client.fetch-registry=false
#对外地址
eureka.client.serviceUrl.defaultZone= http://${eureka.instance.hostname}:${server.port}/eureka
4、启动EurekaServerApplication
访问http://localhost:1111/ 可以看到如下服务注册页面
说明服务注册中心搭建完成
二、高可用注册中心
生产环境中为避免单机故障,我们需要集群和高可用部署。Eureka Server 的高可用实际上就是将自己作为服务想其它服务注册中心注册自己,这样就形成了一组互相注册的服务中心,以实现服务清单 的互相同步,达到高可用的效果。
–接着上面搭建的eureka-server改造–
1、两个注册中心配置文件
application-peer1.properties : peer1中心,将serviceUrl 指向 peer2
spring.application.name=eureka-server
server.port=1111
eureka.instance.hostname=peer1
eureka.client.serviceUrl.defaultZone=http://peer2:1112/eureka/
application-peer2.properties : peer2中心,将serviceUrl 指向 peer1
spring.application.name=eureka-server
server.port=1112
eureka.instance.hostname=peer2
2、启动
本地HOST添加配置,让peer1和peer2能够被访问到(推荐SwitchHosts工具,一键切换hosts,作者官网:http://oldj.net/article/switchhosts/)
127.0.0.1 peer1
127.0.0.1 peer2
通过JAVA命令启动两个注册中心
java -jar eureka-server-1.0.jar --spring.profiles.active=peer1
java -jar eureka-server-1.0.jar --spring.profiles.active=peer2
3、查看效果
通过访问http://peer1:1111/ 和http://peer2:1112/查看配置成功:
*完整项目代码在:*