Feign
http客户端Feign
RestTemplate方式调用存在的问题:
//通过”userservice“这个服务名称代替ip、端口
String url = "http://userservice/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
问题:代码可读性差,编程体验不统一
参数复杂URL难以维护
Feign makes writing java http clients easier
Feign是一个声明式的http客户端,官方地址:https://github.com/OpenFeign/feign
作用:帮助我们优雅的实现http请求的发送,解决上面提到的问题。
一、定义和使用Feign客户端
使用Feign的步骤如下:
(1)引入依赖:
<!--Feign客户端依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
(2)在order-service的启动类添加注解开启Feign的功能:
@EnableFeignClients
(3)编写Feign客户端:
UserClient接口
package cn.itcast.order.clients; import cn.itcast.order.pojo.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); }
主要是基于SpringMVC的注解来声明远程调用的信息,比如:
服务名称:userservice
请求方式:GET
请求路径:/user/{id}
请求参数:Long id
返回值类型:User
package cn.itcast.order.web; import cn.itcast.order.clients.UserClient; import cn.itcast.order.pojo.Order; import cn.itcast.order.pojo.User; import cn.itcast.order.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("order") public class OrderController { @Autowired private OrderService orderService; @Autowired private UserClient userClient; @GetMapping("{orderId}") public Order queryOrderByUserId(@PathVariable Long orderId){ //1、根据id查询订单并返回 Order order = orderService.queryOrderById(orderId); //2、用Feign远程调用 User user = userClient.findById(order.getUserId()); //3、封装user到Order order.setUser(user); //4、返回 return order; } // @Autowired // private RestTemplate restTemplate; // // @GetMapping("{orderId}") // public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) { // //1、根据id查询订单并返回 // Order order = orderService.queryOrderById(orderId); // // //2、利用RestTemplate发起http请求,查询用户 // //String url = "http://localhost:8081/user/" + order.getUserId(); // // //通过”userservice“这个服务名称代替ip、端口 // String url = "http://userservice/user/" + order.getUserId(); // User user = restTemplate.getForObject(url, User.class); // //3、封装user到Order // order.setUser(user); // return order; // } }
Feign的使用步骤
1、引入依赖
2、添加@EnableFeignClients注解
3、编写FeignClient接口
4、使用FeignClient中定义的方法代替RestTemplate