博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot-Feign
阅读量:4303 次
发布时间:2019-05-27

本文共 2027 字,大约阅读时间需要 6 分钟。

1.引用jar包,pom文件

org.springframework.cloud
spring-cloud-starter-feign

2.启动类上面加注解@EnableFeignClients

表示扫描带有@FeignClient注解的接口
添加注解之后的启动类是这个样子

@SpringBootApplication@EnableFeignClientspublic class MyApplication {	public static void main(String[] args) {		SpringApplication.run(MyApplication.class, args);	}}

3.写一个接口并且用@FeignClient注解

前提最好用浏览器或者HTTP工具,比如PostMan测试一下那个被调用的接口,确保被调用的接口是可用的

注意:name与url的区别,如果调用的服务,和我们的服务,不在同一个注册中心,那么此时就需要使用一个url来指定被调用的服务的地址,如果在同一个注册中心,那么不建议使用,因为既然在同一个注册中心,还用url干嘛?那不是和注册中心的理念冲突了么

NOTE:当name与url都存在时,feign会认为这是第三方服务,和你不在同一个注册中心,所以优先使用url

@FeignClient(name="被调用的那个服务在eureka中的名字",value="就是name,它俩一样",url="http://localhost:1234/aaa")public interface MyInterface{	//此处相当于访问http://localhost:1234/aaa/m1?p1=xxxx	//注意:c1是controller的映射,m1是方法映射,而上面的aaa是项目名	@RequestMapping("/c1/m1")	public String method1(@RequestParam("p1") String p1);	//*****注意此处User,挺有意思的,被调用的服务哪怕返回的不会User类,只要字段名字一样,	//值就会传递过来,网上有例子写实现Seralizable接口,全限定名一样什么的,纯属没有任何用,	//spring是使用jackson直接json转换的	@RequestMapping("/c1/m2")	public User method1(@RequestParam("p1") String p1);	//*****注意:以下方式摘自网上,我没有亲自试验过,但是觉得可行,所以我就复制过来了    @RequestLine("GET /user/index")//feign独有的注解方式     String index();    @RequestMapping(value = "/get0/{id}", method = RequestMethod.GET)    User findById(@PathVariable("id") Long id);    @RequestMapping(value = "/get1", method = RequestMethod.GET)    User get1(@RequestParam("id") Long id, @RequestParam("name") String name);    @RequestMapping(value = "/get2", method = RequestMethod.GET)    User get2(@RequestParam Map
map); @RequestMapping(value = "/hello2", method=RequestMethod.GET) User hello2(@RequestHeader("name") String name, @RequestHeader("age") Integer age); @RequestMapping(value = "/hello3", method=RequestMethod.POST) String hello3(@RequestBody User user); //****************摘抄结束************

4.哪里需要调用,哪里就直接@Autowired,比如在某个Service中使用就

@Servicepublic class MyService{	@Autowired	MyInterface myInterface;}

5.OJBK,没有第五步,Feign使用完毕

转载地址:http://ethws.baihongyu.com/

你可能感兴趣的文章
删远端分支报错remote refs do not exist或git: refusing to delete the current branch解决方法
查看>>
python multiprocessing遇到Can’t pickle instancemethod问题
查看>>
APP真机测试及发布
查看>>
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>
一个异步网络请求的坑:关于NSURLConnection和NSRunLoopCommonModes
查看>>
iOS 如何放大按钮点击热区
查看>>
ios设备唯一标识获取策略
查看>>
获取推送通知的DeviceToken
查看>>
Could not find a storyboard named 'Main' in bundle NSBundle
查看>>
CocoaPods安装和使用教程
查看>>
Beginning Auto Layout Tutorial
查看>>
block使用小结、在arc中使用block、如何防止循环引用
查看>>
iPhone开发学习笔记002——Xib设计UITableViewCell然后动态加载
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Swift code into Object-C 出现 ***-swift have not found this file 的问题
查看>>
为什么你的App介绍写得像一坨翔?
查看>>
RTImageAssets插件--@3x可自动生成@2x图片
查看>>
iOS开发的一些奇巧淫技
查看>>
常浏览的博客和网站
查看>>