SpringCloud |
您所在的位置:网站首页 › 十四五乡村旅游发展 › SpringCloud |
文章目录
Feign远程调用Feign替代RestTemplate1)引入依赖2)添加注解3)编写Feign的客户端4)测试5)总结
Feign远程调用
先来看我们以前利用RestTemplate发起远程调用的代码: 存在下面的问题: •代码可读性差,编程体验不统一 •参数复杂URL难以维护 Feign是一个声明式的http客户端,官方地址:https://github.com/OpenFeign/feign 其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。 Feign替代RestTemplateFegin的使用步骤如下: 1)引入依赖我们在order-service服务的pom文件中引入feign的依赖: org.springframework.cloud spring-cloud-starter-openfeign 2)添加注解在order-service的启动类添加注解开启Feign的功能: 3)编写Feign的客户端在order-service中新建一个接口,内容如下: package cn.itcast.order.client; 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这样,Feign就可以帮助我们发送http请求,无需自己使用RestTemplate来发送了。 4)测试修改order-service中的OrderService类中的queryOrderById方法,使用Feign客户端代替RestTemplate: 是不是看起来优雅多了。 5)总结使用Feign的步骤: ① 引入依赖 ② 添加@EnableFeignClients注解 ③ 编写FeignClient接口 ④ 使用FeignClient中定义的方法代替RestTemplate |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |