OpenFeign 是一个声明式的 HTTP 客户端,它简化了 HTTP 客户端的开发。使用 OpenFeign,只需要创建一个接口并注解,就能很轻松的调用各服务提供的 HTTP 接口。OpenFeign 默认集成了 Ribbon,默认实现了负载均衡。
在 SpringCloud-Main 中创建一个 Module 子项目 取名 SpringCloud-feign
添加 Maven 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
<exclusions>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
然后修改配置文件:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8088
spring:
application:
name: feign
启动类添加注解@EnableFeignClients
如果我们要使用 OpenFeign 声明式 HTTP 客户端,必须要在启动类加入这个注解,以开启 OpenFeign。
创建一个接口 ApiService,并且通过注解配置要调用的服务地址:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author 作者 : 小布
* @version 创建时间 : 2019年5月8日 上午10:33:10
* @explain 类说明 :
*/
@FeignClient(value = "SpringCloud-client-A",fallback = ApiServiceError.class)
public interface ApiService {
@RequestMapping(value = "/hello/index",method = RequestMethod.GET)
String index();
}
然后可以在测试类中测试:
@Autowired
private ApiService apiService;
@Test
public void test(){
try {
System.out.println("------------------"+apiService.index());
System.out.println("------------------"+apiService.index());
}catch (Exception e){
e.printStackTrace();
}
}
上一篇 Spring Cloud (三) 服务网关 gateway