Eureka客戶端依賴項添加到服務應用程序的構建中:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
applicationl.yml
spring:
application:
name: myFirstservice2
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
server:
port: 0
說明:
spring.application.name:在Eureka中註冊服務的名稱,設置此屬性後,可以通過服務名稱myFirstservice2查找服務。
因爲你只會通過Eureka查詢服務,所以他們正在監聽的端口並不重要 - 尤里卡知道他們在哪個端口。因此,爲了避免在本地運行時發生潛在的端口衝突,可以將端口設置爲0:
eureka.client.service-url屬性:需要指定Eureka服務器的位置。這與Eureka服務器配置文件中的地址一至
調用微服務
@RestController
@RequestMapping(path = "/client",produces = "application/json")
@CrossOrigin(origins = "*")
public class IngredientServiceClient {
private RestTemplate rest;
public IngredientServiceClient(@LoadBalanced RestTemplate rest){
this.rest=rest;
}
@GetMapping("/taco")
public Taco getTaco(){
//調用微服務myFirstservice
return rest.getForObject("http://myFirstservice/design/taco",Taco.class);
}
@GetMapping("/mytest")
public String getString(){
return "lsjdlfjlksdjlf";
}
}
@RestController
@RequestMapping(path="design",produces = "application/json")
public class MyserviceController {
@GetMapping(path = "/taco")
public Taco mytest(){
Taco taco=new Taco();
taco.setId(99);
taco.setName("雞腿漢堡");
taco.setTitle("麥當勞");
return taco;
}
}
@SpringBootApplication
public class MyeurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(MyeurekaClientApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}