1. 创建服务注册中心
首先搭建一个Spring Boot快速启动框架,这里我们使用多模块的方式搭建。创建好Spring Boot项目后删除其它文件只保留一个pom文件
2. 创建一个服务注册中心(EurekaServer)
- 在刚刚搭建的porject上新建一个module,依然使用Spring Boot初始化,并在初始化时勾选Eureka Server组件
- 在启动类上添加注解
@EnableEurekaServer
以表明这是一个EurekaServer
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- application.yml配置文件
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- 查看EurekaServer是否正常启动
在浏览器输入http://localhost:8761
此时会显示
No instances available
,因为我们还没有注册服务
3. 创建一个服务提供者(EurekaClient)
- 同样继续新建一个module并添加EurekaDiscovery和web组件
- 同样的在启动类上添加注解
@EnableEurekaClient
以表明这是一个EurekaClient
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaClientApplication {
@Value("${server.port}")
String port;
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
@RequestMapping("/index")
public String index(String name) {
return "name:" + name + ",port:" + port;
}
}
- application.yml配置
server:
port: 8762
spring:
application:
name: service-hello
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- 查看EurekaClient是否正常启动
在浏览器输入http://localhost:8762/index?name=狗子
此时服务已经正常注册启动了,并且在EurekaServer后台可以看到