我們將一個大的應用拆成多個小的服務之后,緊接著的一個問題就是,原本都在一個項目里,方法我可以隨便調用,但是拆開后,原來的方法就沒法直接調用了,這時候要怎么辦?
Spring Cloud提供了feign,能夠輕松解決這個問題,feign能讓我們調用遠程服務方法就像調用本地方法一樣,調用者完全感覺不到實在調用遠程服務。
其底層其實就是使用了RPC,對網絡的請求和響應做了解析,在這里對RPC先不做講解,我們重點來了解如何使用feign來調用其他微服務。
feign這個功能是不是聽起來很神奇,但是用起來確實很簡單,我們一起來看看。
實操O(∩_∩)O
1、首先復制一個service-a的項目,我們起名叫service-b
2、在service-b的pom.xml文件中,添加feign的依賴
org.springframework.cloud
spring-cloud-starter-openfeign
3、在應用主類添加@EnableFeignClients,開啟feign支持
package com.itzhimei.serviceb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceBApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceBApplication.class, args);
}
}
4、在service-b中添加一個抽象接口ServiceA
package com.itzhimei.serviceb.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("service-a")
public interface ServiceA {
@GetMapping(value = "/getInfo")
public String getInfo();
}
這個接口的作用就是,讓serviceb調用servicea的方法就像調用本地方法一樣。class上的注解@FeignClient(“service-a”),就表示通過serviceA的serviceId,找到serviceA服務,通過@GetMapping(value = “/getInfo”)來對應到serviceA中的方法。
5、最后就是調用ServiceA了,寫一個調用的Controller
package com.itzhimei.serviceb.controller;
import com.itzhimei.serviceb.feign.ServiceA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceBController {
@Autowired
ServiceA serviceA;
@RequestMapping(value="helloFeign", method = RequestMethod.GET)
public String helloFeign() {
return serviceA.getInfo();
}
}
輸出結果:名字是:張三,年齡是:20
到這里,微服務的相互調用就成功了,是不是超級簡單,通過幾步配置,就完成了原來復雜的網絡之間的調用。