Spring Boot2.0實現微服務呼叫
服務提供者:提供對應的介面實現方法
服務消費者:建立對應的方法介面(表明指向服務提供者),並在控制器中呼叫
=======================================
服務提供者:
建立控制器(實現介面內容)
@RestController
public class HelloController { ******
@GetMapping("/hello/{name}")
public String index(@PathVariable String name){
return "this is admin ,hello!" + name;
}
}
--------------------
入口檔案
@SpringBootApplication
@EnableEurekaClient
public class AmncloudAdminApplication {
public static void main(String[] args) {
SpringApplication.run(AmncloudAdminApplication.class, args);
}
}
-----------------
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
======================================================
服務消費者:
介面
@FeignClient(name= "amncloud-admin") ******重點
public interface HelloRemote {
@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") String name);
}
------------------------
控制器
@RestController
public class UcenterController {
@Autowired ******重點
HelloRemote helloRemote;
@GetMapping("/hello/{name}")
public String index(@PathVariable("name") String name) {
return helloRemote.hello(name);
}
}
-------------------------
入口檔案
@SpringBootApplication
@EnableFeignClients #注意與服務提供者的不同*********重點
@EnableDiscoveryClient
public class AmncloudUcenterApplication {
public static void main(String[] args) {
SpringApplication.run(AmncloudUcenterApplication.class, args);
}
}
-------------------
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>