1.首先搭建一个普通的Spring Boot项目,结构如下:
2.对pom.xml中的依赖进行修改
4.0.0
com.czx
eureka-server
0.0.1-SNAPSHOT
jar
eureka-server
http://maven.apache.org
org.springframework.boot
spring-boot-starter-parent
1.5.6.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.cloud
spring-cloud-starter-eureka-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
3.在资源包下新建application.properties的资源文件
server.port=1010 // 将服务器端口号修改为1010(根据自己情况可以另做修改)
eureka.instance.hostname=localhost // 表示访问的是本地
eureka.client.register-with-eureka=false // 默认情况下,这个应用会向注册中心注册自己,设置为false表示这种默认行为
eureka.client.fetch-registry=false // 表示不会去检索其他服务
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
4.在项目的支行入口添加注解
@SpringBootApplication
@EnableEurekaServer
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
5.启动程序,访问http://localhost:1010/eureka/,出现如下效果,表示服务注册中心已经搭建好了
6.注册服务提供者
新建一个Spring Boot工程,在pom.xml文件中进行修改。
4.0.0
com.czx
provider
war
0.0.1-SNAPSHOT
provider Maven Webapp
http://maven.apache.org
org.springframework.boot
spring-boot-starter-parent
1.5.6.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
7.和之前步骤一样,创建一个application.properties文件
spring.application.name=hello-service
eureka.client.service-url.defaultZone=http://localhost:1010/eureka
8.随意创建一个类
package com.czx.controller;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private DiscoveryClient client;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() {
List instances = client.getInstances("hello-service");
for (int i = 0; i < instances.size(); i++) {
logger.info("/hello,host:" + instances.get(i).getHost() + ",service_id:" + instances.get(i).getServiceId());
}
return "Hello World";
}
}
9.最后进行主函数入口,启动程序,有一点需要注意,之前注册服务的程序不能停,正常会出现如下效果图: