我是
靠谱客的博主
细腻画笔,这篇文章主要介绍
第七篇:Feign访问服务集群,现在分享给大家,希望可以做个参考。
一、 什么是 Feign ?
Feign 是一种声明式、模板化的 HTTP 客户端,在 Spring Cloud 中使用 Feign,可以做到使用 HTTP
请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是
个 HTTP 请求。
Feign 的灵感来源于 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客户端编写更方便,旨在通过最少的资源和代码来实现和 HTTP API 的连接。
二:pom依赖
springboot2.0以前的依赖
| 1 2 3 4 | <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> |
Finchley.SR1版本 feign的pom依赖
| 1 2 3 4 | <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> |
说明:由于很多模块都要用,可以直接在父工程依赖,同时feign无需指定version,因为springclould中已经指定了版本
三:@EnableFeignClients启动feign (在调用方启动该注解)
| 1 2 3 4 5 6 7 8 9 | @SpringBootApplication @EnableEurekaClient @EnableFeignClients public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } } |
四:定义服务接口
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.wendao.provider.consumer.feign; import com.wendao.provider.consumer.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; //spring-cloud-service-provider为服务提供者的应用名 @FeignClient(name="spring-cloud-service-provider") public interface IuserBiz { @RequestMapping(value = "/user/{userId}") User findUserById(@PathVariable(name = "userId") Integer uesrId); } |
这里切记一点:虽然路径中参数名叫userId和方法形参中参数名一致,但是@PathVariable中还是要指定。
五:调用
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | @RestController public class ConsumerController { @Autowired private IuserBiz iuserBiz; @RequestMapping("/findOne/{id}") public User findOne(@PathVariable Integer id){ return iuserBiz.findUserById(id); } } |
小结:服务提供者的代码不用做任何修改,只需要在服务消费者这边修改即可
最后
以上就是细腻画笔最近收集整理的关于第七篇:Feign访问服务集群的全部内容,更多相关第七篇内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复