Springboot框架,SpringBoot-Feign

 2023-10-15 阅读 31 评论 0

摘要:1.引用jar包,pom文件 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-feign</artifactId> </dependency> 2.啟動類上面加注解@EnableFeignClients 表示掃描帶有@FeignClient注解的接

1.引用jar包,pom文件

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

2.啟動類上面加注解@EnableFeignClients
表示掃描帶有@FeignClient注解的接口
添加注解之后的啟動類是這個樣子

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

3.寫一個接口并且用@FeignClient注解
前提最好用瀏覽器或者HTTP工具,比如PostMan測試一下那個被調用的接口,確保被調用的接口是可用的

Springboot框架?注意: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<String, Object> 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中使用就

@Service
public class MyService{@AutowiredMyInterface myInterface;
}

5.OJBK,沒有第五步,Feign使用完畢

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/137104.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息