SpringBoot-Feign

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测试一下那个被调用的接口,确保被调用的接口是可用的

@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{
	@Autowired
	MyInterface myInterface;
}

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

猜你喜欢

转载自blog.csdn.net/u011624903/article/details/86982900