由于兼容性问题,本例中采用spring boot 1.5.x,首先点击这里创建一个gradle工程,然后导入到idea.
添加build.gradle相关依赖
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Edgware.SR4'
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
添加@EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class CloudApplication {
public static void main(String[] args) {
SpringApplication.run(CloudApplication.class, args);
}
}
更新配置文件,配置服务名称,端口等等。
spring.application.name=eureka-server
server.port=1111
eureka.instance.hostname=localhost
# 关闭保护机制
#eureka.server.enable-self-preservation=false
# 关闭自己注册自己
eureka.client.register-with-eureka=false
# 不需要检索服务
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
下面就可以启动服务了,然后打开http://localhost:1111/控制台(目前没有服务注册
)
同样创建一个gradle工程,配置为服务注册客户端。
在build.gradle导入相关依赖
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Edgware.SR4'
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
compile 'org.slf4j:slf4j-api:1.7.14'
compile('org.springframework.cloud:spring-cloud-starter-eureka')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
修改配置文件application.properties
spring.application.name=hello-service
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
server.port=8081
启动类添加@EnableDiscoveryClient,激活eureka中的DiscoveryClient的实现,如下:
@EnableDiscoveryClient
@SpringBootApplication
public class CloudApplication {
public static void main(String[] args) {
SpringApplication.run(CloudApplication.class, args);
}
}
最后,添加一个controller,方便服务测试,如下:
@RestController
public class HelloController {
@Autowired
private DiscoveryClient client;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() throws Exception {
ServiceInstance instance = client.getLocalServiceInstance();
logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
return "Hello World";
}
启动服务,然后查看eureka控制台,发现有新服务注册,测试服务接口http://desktop-7brumlo:8081/hello