文章实例使用的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的服务。