一、RestTemplate问题
先来看我们以前利用RestTemplate发起远程调用的代码:
存在下面的问题:
- 代码可读性差,编程体验不统一
- 参数复杂URL难以维护
Feign是一个声明式的http客户端,官方地址:GitHub - OpenFeign/feign: Feign makes writing java http clients easier
其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。
二、Feign替代RestTemplate
Fegin的使用步骤如下
1)引入依赖
我们在order-service服务的pom文件中引入feign的依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
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的注解来声明远程调用的信息,比如:文章来源:https://www.toymoban.com/news/detail-453704.html
服务名称:userservice<文章来源地址https://www.toymoban.com/news/detail-453704.html
到了这里,关于SpringCloud --- Feign远程调用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!