一、什么是OpenFeign?
首先要知道何为Feign?
-
Feign是SpringCloud组件中一个轻量级RESTFul的HTTP客户端。
-
Feign内置了Ribbon实现客户端请求的负载均衡。但是Feign是不支持Spring MVC注解的,所以便有了OpenFeign,OpenFeign在Feign的基础上支持Spring MVC注解比如 @RequestMapping等。
-
OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,通过动态代理生成实现类,实现类做负载均衡并调用其他服务。
OpenFeign简介
OpenFeign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用OpenFeign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。
二、整合OpenFeign
1. 完善openfeign-stu项目
1. openfeign-stu项目的pom.xml添加openfeign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 新版本的默认使用loadbalancer,而不是ribbon-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
2. 完善feign-api项目
我们需要集中化管理API,就可以通过接口统一管理,需要新增商品服务的接口类。
在项目中新建com.wq.feign.api.clients.ProductFeignClient类,内容如下:
package com.wq.feign.api.clients;
import com.wq.feign.api.domain.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Component
@FeignClient(name="feign-provider-8081")
public interface ProductProviderClient {
/**
* 查询
* @return
*/
@GetMapping("product/provider/get/info")
public Result getServiceInfo();
/**
* 查询
* @param id
* @return
*/
@GetMapping("product/provider/get/{id}")
public Result selectById(@PathVariable("id") Long id);
}
3. 完善feign-consumer项目
1. 主启动类加上注解@EnableFeignClients注解
@EnableFeignClients申明该项目是Feign客户端,扫描对应的feign client。
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableFeignClients(basePackages = {
"com.wq.feign.api.clients"})
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
2. 修改消费者Controller
现在接口已经封装在了ProductFeignClient里面了,因此在消费者Controller,我们不用再通过微服务名加地址去访问了,修改后的Controller如下:
@RestController
public class ProductConsumerController {
@Resource
private ProductProviderClient productProviderClient;
/**
* 查询
* @param id
* @return
*/
@GetMapping("product/consumer/get/{id}")
public Result selectById(@PathVariable("id") Long id){
return productProviderClient.selectById(id);
}
}
4. 完善feign-provider项目
openfeign不同于dubbo,feign-provider不需要配置任何OpenFeign的东西
5. 测试
现在我们已经配置好了消费端通过OpenFeign调用远程接口,接下来就是重启消费端服务ConsumerApplication,重启后,浏览器访问消费者API可以得到正常的结果