http客户端Feign
http客户端Feign
RestTemplate方式调用存在的问题
先来看我们以前利用RestTemplate发起远程调用的代码:

存在下面的问题:
代码可读性差,编程体验不统一
参数复杂URL难以维护
Feign是一个声明式的http客户端,官方地址:https://github.com/OpenFeign/feign
其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。

使用Feign的步骤如下:
引入依赖:
<!--feign客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在order-service的启动类添加注解开启Feign的功能:
@MapperScan("com.po.mapper")
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
编写Feign客户端:
package com.po.client;
import com.po.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient("userservice")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
用Feign客户端代替RestTemplate
public class OrderController {
@Autowired
private UserClient userClient;
@Autowired
private OrderService orderService;
@GetMapping("{orderId}")
public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
User user1=userClient.findById(Long.parseLong("1"));
System.out.println(user1);
// 根据id查询订单并返回
return orderService.queryOrderById(orderId);
}
}
将FeignClient抽取为独立模块,并且把接口有关的POJO、默认的Feign配置都放到这个模块中,提供给所有消费者使用
浙公网安备 33010602011771号