本文共 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 Mapmap); @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/