跳转至

远程调用OpenFeign

约 393 个字 149 行代码 预计阅读时间 3 分钟

介绍

基本使用

引入依赖(谁发起远程调用,谁引入依赖)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- loadbalancer依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

开启OpenFeign功能

1
2
3
4
5
6
7
@EnableFeignClients // 开启OpenFeign功能
@SpringBootApplication
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}

编写Feign客户端

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 在注册中心中找value对应的服务,path表示请求的统一前缀
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
    // 通过id查询
    @RequestMapping("/{id}")
    Product getProductById(@PathVariable Integer id);

    // 接收一个参数,不能省略@RequestParam
    @RequestMapping("/p1")
    String p1(@RequestParam("id") Integer id);

    // 接收多个参数
    @RequestMapping("/p2")
    String p2(@RequestParam("id") Integer id, @RequestParam("name") String name);

    // 接收一个对象
    // OpenFeign客户端接收一个对象需要使用@SpringQueryMap
    @RequestMapping("/p3")
    String p3(@SpringQueryMap Product product);

    // 接收一个JSON
    @RequestMapping("/p4")
    String p4(@RequestBody Product product);
}

修改远程调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ProductApi productApi;

    public Order getOrderById(Integer id) {
        Order order = orderMapper.selectOrderById(id);
        Product product = productApi.getProductById(order.getProductId());
        order.setProduct(product);
        return order;
    }

    // 接收一个参数
    public String p1(Integer id) {
        return productApi.p1(id);
    }

    // 接收多个参数
    public String p2(Integer id, String name) {
        return productApi.p2(id, name);
    }

    // 接收一个对象
    public String p3(Product product) {
        return productApi.p3(product);
    }

    // 接收一个JSON
    public String p4(Product product) {
        return productApi.p4(product);
    }
}

OpenFeign最佳实践

下面的两种方式,都会创建一个单独的API模块,其他模块要使用API模块,就需要先将API模块使用Maven的install先把API模块打包安装到本地仓库

如果是服务器部署并且不使用Maven中央仓库或者私服的情况下,则可以考虑本地读取:

  1. 在开发环境下先使用Maveninstall把API模块打包安装到本地仓库
  2. 修改引入了API模块的其他模块的pom文件,在依赖配置中添加如下的代码,然后再打包该模块:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>product-api</artifactId>
        <version>1.0-SNAPSHOT</version>
        <!-- scope 为system. 此时必须提供systemPath即刚才安装的本地依赖路径. 表⽰maven不会去中央
        仓库查找依赖 注意使用斜杠而不是反斜杠-->
        <scope>system</scope>
        <systemPath>D:/Maven/.m2/repository/org/example/product-api/1.0-SNAPSHOT/product-api-1.0-SNAPSHOT.jar</systemPath>
    </dependency>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- 打包时就会把上面那个本地的 product-api.jar 一并塞进最终的可执行 jar 里 -->
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
  3. 将可执行的jar上传到服务器即可,此时不需要再考虑API模块,因为其打包结果已经塞进可执行的jar中了

继承

本质:让API直接继承公共接口,调用实现公共接口的Controller提供的方法

Product-API模块的公共接口:

1
2
3
4
5
// 定义接口,供服务提供方的Controller实现
public interface ProductInterface {
    @RequestMapping("/{id}")
    Product getProduct(@PathVariable Integer id);
}

Product-Service模块的Controller实现Product-API模块的接口:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@RequestMapping("/product")
@RestController
public class ProductController implements ProductInterface {
    @Autowired
    private ProductService productService;

    @RequestMapping("/{id}")
    @Override
    public Product getProduct(@PathVariable Integer id) {
        return productService.getProductById(id);
    }
}

在服务调用方Order-Service中定义API继承Product-API的接口:

1
2
3
4
5
6
// 服务消费者的api接口继承接口,该接口中就可以使用父类中的接口
// 根据多态调用实现的方法
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi extends ProductInterface {

}

抽取

本质:让服务提供方自行确定接口的定义,服务使用方直接扫描引入即可调用方法

Product-API模块(需要引入OpenFeign依赖)提供接口:

1
2
3
4
5
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
    @RequestMapping("/{id}")
    Product getProduct(@PathVariable Integer id);
}

Product-Service模块实现接口:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@RequestMapping("/product")
@RestController
public class ProductController implements ProductApi {
    @Autowired
    private ProductService productService;

    @RequestMapping("/{id}")
    @Override
    public Product getProduct(@PathVariable Integer id) {
        return productService.getProductById(id);
    }
}

Order-Service(需要引入LoadBalancer依赖)需要告诉OpenFeign扫描的包或者客户端类对象:

1
2
3
4
5
6
7
8
9
@EnableFeignClients(clients = {ProductApi.class}) // 扫描其他模块下的ProductApi类
// 也可以扫描Api所在的包
// @EnableFeignClients(basePackages = {"org.epsda.productapi.api"}) // 看ProductApi类所在的包名
@SpringBootApplication
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}