1. 工程结构
为了演示方便所以建三个工程,实际生产是一个工程配置三份,端口不同
- eureka-provider-8001
- eureka-provider-8002
- eureka-provider-8003
2. pom文件
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
3. yml配置
修改三台的端口即可
server:
port: 8001
eureka:
client:
serviceUrl:
defaultZone: http://eureka-server-7001:7001/eureka/,http://eureka-server-7002:7002/eureka/,http://eureka-server-7003:7003/eureka/
# defaultZone: http://eureka-server-8001:7001/eureka/
instance:
instance-id: eureka-provider-7001 # 服务名称
prefer-ip-address: true # 显示ip地址
info: # 点击注册列表未服务出现的信息
app.name: springcloud
company.name: www.honor.com
build.artifactId: @project.artifactId@
build.version: @project.version@
spring:
application:
name: eureka-provider # 三台服务必须一致
4. 主启动类
根据项目修改为EurekaProvider8001Application、EurekaProvider8002Application、EurekaProvider8003Application即可
@SpringBootApplication
@EnableEurekaClient
public class EurekaProvider8001Application {
public static void main(String[] args) {
SpringApplication.run(EurekaProvider8001Application.class, args);
}
}
5. 增加服务
// Controller
@RestController
public class HelloController {
@Autowired
private IHelloService helloService;
@RequestMapping("/hello/{name}")
public String sayHello(@PathVariable String name) {
return helloService.sayHello(name);
}
}
//ServiceImpl
@Service
public class HelloServiceImpl implements IHelloService {
@Autowired
private HttpServletRequest request;
public String sayHello(String name) {
return "Hello " + name + ", This port is " + request.getServerPort();
}
}
6. 验证
- 服务注册中心可以三台注册的服务
- 确保三台服务都是可以正常使用的