先来看我们以前利用RestTemplate发起远程调用的代码
String url ="http://userservice/user/"+order.getUserId();
User user = restTemplate.getForObject(url,User.class);
存在下面问题:
① 代码可读性差,编程提验不统一
② 参数复杂URL难以维护
Feign是一个声明式的http客户端.
① 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
② 在order-service的启动类添加注解开启Feign的功能
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
③ 编写Feign的接口
@FeignClient("userservice")
public interface UserClient{
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}