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. 驗證
- 服務註冊中心可以三臺註冊的服務
- 確保三臺服務都是可以正常使用的