赞
踩
一、注册中心编码
1.使用idea创建一个spring boot项目,pom如下:
4.0.0
com.eureka
ser
0.0.1-SNAPSHOT
jar
ser
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
Finchley.RELEASE
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
2.这里开发3个样例,组成集群。3个样例的pom不变,application.yml如下:
#样例1:
server:
port:8888eureka:
instance:
hostname: centos7-01client:
registerWithEureka:falsefetchRegistry:falseserviceUrl:
defaultZone: http://centos7-02:8888/eureka/,http://centos7-03:8888/eureka/
#样例2:
server:
port:8888eureka:
instance:
hostname: centos7-02client:
registerWithEureka:falsefetchRegistry:falseserviceUrl:
defaultZone: http://centos7-01:8888/eureka/,http://centos7-03:8888/eureka/
#样例3:
server:
port:8888eureka:
instance:
hostname: centos7-03client:
registerWithEureka:falsefetchRegistry:falseserviceUrl:
defaultZone: http://centos7-01:8888/eureka/,http://centos7-02:8888/eureka/
3.这些样例的java代码一样:
package com.eureka.ser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServerpublic classSerApplication {public static voidmain(String[] args) {
SpringApplication.run(SerApplication.class, args);
}
}
4.打包,要在项目的根路径
二、部署运行
1.这里开启3台虚拟机,域名分布为centos7-01 centos7-02 centos7-03,上面的yml文件的hostname与之对应。将这3个jar文件分别运行
2.查看结果,在本机访问虚拟机时,需要关闭虚拟机的防火墙(或者开放端口);
把url换为centos7-02 centos7-03,会看到类似的结果,说明3台服务已经协调运行了
三、客户端注册
1. 新创建一个spring boot项目,其中pom文件如上,yml和java代码如下,然后按照上面的方式打包运行
eureka:
client:
serviceUrl:
defaultZone: http://centos7-02:8888/eureka/ ###这里只向centos7-02注册,会向另外两台会同步过去
server:
port:80spring:
application:
name: eureka-cli
package com.cloud.eurekacli01;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
@SpringBootApplication
@EnableEurekaClient
@RestControllerpublic classEurekaCli01Application {public static voidmain(String[] args) {
SpringApplication.run(EurekaCli01Application.class, args);
}@RequestMapping("/")publicString index(){
SimpleDateFormat sdf= new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String time= sdf.format(newDate());return "current time is"+time;
}
}
2. 查看注册结果,打开3个中任意一个注册界面,都会有如下结果,说明客户端已经成功在集群上注册了
3.访问客户端 (客户端是在本地启动的)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。