天天看點

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測試一下那個被調用的接口,確定被調用的接口是可用的

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

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

繼續閱讀