文章實例使用的Spring Cloud版本爲Finchley.SR1,Spring Boot版本爲2.0.4。
1 Spring Cloud Feign
Spring Cloud Feign是一套基於Netflix Feign實現的聲明式服務調用客戶端。使用Spring Cloud Feign,我們只需創建一個接口並用註解的方式來配置它,即可完成對服務提供方的接口綁定,簡化了在使用Spring Cloud Ribbon時自行封裝服務調用客戶端的開發量。
2 實例
2.1 創建Spring Boot應用,引入相關依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.2 application.properties指定註冊中心
spring.application.name=feign-consumer
server.port=3002
#項目信息
info.name=${spring.application.name}
info.server.ip-address=${spring.cloud.client.ip-address}
info.server.port=${server.port}
#實例默認通過使用域名形式註冊到註冊中心:false
eureka.instance.prefer-ip-address=true
#實例名
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#註冊中心地址
eureka.client.serviceUrl.defaultZone=http://peer2:1002/eureka/,http://peer2:1003/eureka/
2.3 修改應用主類
@SpringCloudApplication
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
2.4 新建接口,綁定要調用的服務
@FeignClient("EUREKA-CLIENT")
public interface HelloFeignClient {
@GetMapping("/hello")
String hello();
}
2.5 服務調用
@RestController
public class ConsumerController {
@Autowired
private HelloFeignClient helloFeignClient;
@GetMapping("/feign-consumer/hello")
public String dc() {
return helloFeignClient.hello();
}
}
2.6 啓動應用
訪問http://localhost:3002/feign-consumer/hello 可以看到成功調用到了EUREKA-CLIENT的服務。