Spring Cloud Feign:服務通信
Spring Cloud Feign是簡化Java HTTP客戶端開發的工具,它的靈感來自於Retrofit、JAXRS-2.0和WebSocket。接下來將展示一個入門Demo。
開發環境 | 版本 |
---|---|
IDEA | 2018.2.6 |
JDK | 1.8 |
Spring Boot | 2.1.0 |
Spring Cloud | Greenwich.M1 |
新建項目
在IDEA中通過Spring Initializr創建項目,選擇Spring Boot 2.1.0版本、選擇Maven依賴Web、Eureka Discovery(Cloud Discovery中)和Feign(Cloud Routing中)。
<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.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
加入註解
在入口類添加@EnableEurekaClient和@EnableFeignClients註解。
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
添加配置
在文件application.yml添加配置。
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
# hostname: ConsumerName
spring:
application:
name: consumer
編寫接口
在上一篇的provider項目中,新建簡單的Controller,代碼如下,運行provider項目,訪問http://localhost:8081/hello/chung可得到Hello Chung By Provider
。
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/chung")
public String helloChung(){
return "Hello Chung By Provider";
}
}
在本篇的新項目consumer中新建接口和Controller,代碼如下:
@FeignClient(name = "provider")
public interface ProviderClient {
@RequestMapping(value = "/hello/chung")
String hello();
}
@RestController
@RequestMapping("hello")
public class HelloController {
@Autowired
private ProviderClient providerClient;
@GetMapping("/consumer")
public String hello(){
return providerClient.hello();
}
}
運行項目
在VM options設置-DServer.port=8091,運行consumer項目,可以在Eureka頁面看到本項目註冊成功,訪問http://localhost:8091/hello/consumer同樣可以得到Hello Chung By Provider
,證明服務間通信正常。