【Spring Cloud 02】将微服务注册到Eureka
2021-02-24 10:45:36
新建一个微服务Module,名叫`foo-svc`
pom依赖
```xml
<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>
</dependencies>
```
主启动类
```java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableEurekaClient
public class FooApplication {
public static void main(String[] args) {
SpringApplication.run(FooApplication.class, args);
}
@GetMapping("/version")
public String version() {
return "foo v1";
}
}
```
application.yml
```yaml
server:
port: 8001
spring:
application:
name: foo-service
eureka:
instance:
hostname: foo01
instance-id: ${eureka.instance.hostname}:${server.port}
prefer-ip-address: true # 使用IP
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://your-eureka-server-ip:8761/eureka/
```
注意替换 `your-eureka-server-ip`为你真实的Eureka服务器IP
构建jar包上传到服务器,并启动后,到注册中心查看是否注册成功