一、搭建項(xiàng)目

image.png
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
這里使用的boot版本為2.2.2.RELEASE,cloud版本為Hoxton.SR1。
二、修改啟動(dòng)類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class AppUserApplication {
public static void main(String[] args) {
SpringApplication.run(AppUserApplication.class, args);
}
}
@EnableEurekaClient這個(gè)注解就代表著這個(gè)服務(wù)是Eureka Client。當(dāng)然也可以不寫,一樣會(huì)注冊到Eureka Server上。但我習(xí)慣寫上,看起來更明了。
從Spring Cloud Edgware版本開始,@EnableDiscoveryClient 或@EnableEurekaClient 可省略。只需加上相關(guān)依賴,并進(jìn)行相應(yīng)配置,即可將微服務(wù)注冊到服務(wù)發(fā)現(xiàn)組件上。
不同點(diǎn):@EnableEurekaClient只適用于Eureka作為注冊中心,@EnableDiscoveryClient 可以是其他注冊中心。
application.yml
spring:
application:
name: appUser
server:
port: 2020
eureka:
client:
service-url:
defaultZone: http://localhost:1999/eureka
instance:
hostname: localhost
instance-id: ${eureka.instance.hostname}::${server.port}
prefer-ip-address: true

image.png
如果在Eureka Server的控制臺(tái)出現(xiàn)這個(gè)問題:
Connect to localhost:8761 timed out則需要在Eureka Server的配置文件中加入
service-url: defaultZone: http://localhost:1999/eureka
spring:
application:
name: eureka-gj #服務(wù)名
server:
port: 1999 #eureka 默認(rèn)端口為8761
eureka:
client:
register-with-eureka: false #是否注冊到eureka上 默認(rèn)為true 但是我這個(gè)是作為Eureka Server的,所以不需要注冊
fetch-registry: false #是否從Eureka Server上獲取注冊信息
service-url:
defaultZone: http://localhost:1999/eureka #注冊地址
registered-replicas 被重新賦值, 默認(rèn)的8761被覆蓋, 一直嘗試連接的錯(cuò)誤也不會(huì)再出現(xiàn)了!
提供接口
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/user")
public class UserController {
@GetMapping
public String getUser(){
return "調(diào)用成功";
}
}