使用Spring Cloud Feign做爲HTTP客戶端調用遠程HTTP服務

若是你的項目使用了SpringCloud微服務技術,那麼你就可使用Feign來做爲http客戶端來調用遠程的http服務。固然,若是你不想使用Feign做爲http客戶端,也可使用好比JDK原生的URLConnection、Apache的Http Client、Netty的異步HTTP Client或者Spring的RestTemplate。spring

 

那麼,爲何咱們要使用Feign呢?json

首先咱們的項目使用了SpringCloud技術,而Feign能夠和SpringCloud技術無縫整合。而且,你一旦使用了Feign做爲http客戶端,調用遠程的http接口就會變得像調用本地方法同樣簡單。api

下面就看看Feign是怎麼調用遠程的http服務的吧。微信

(1)首先你得引入Feign依賴的jar包:app

gradle依賴:異步

compile "org.springframework.cloud:spring-cloud-netflix-core:1.3.2.RELEASE"

Maven依賴:ide

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-netflix-core</artifactId>
    <version>1.3.2.RELEASE</version>
</dependency>

 

(2)在properties配置文件中配置要調用的接口的URL路徑(域名部分)微服務

url.xapi=http://xapi.xuebusi.com

 

(2)聲明要調用的遠程接口gradle

/**
 * Created by SYJ on 2017/8/11.
 */
@FeignClient(name = "xapi", url = "${url.xapi}")
@RequestMapping(value = "/Resume", produces = {"application/json;charset=UTF-8"})
public interface ResumeClient {
    @RequestMapping(value = "/OperateResume", method = RequestMethod.POST)
    ResultModel sendInterviewRD(@RequestBody FeedBackDto feedBackDto);
}

說明:url

@FeignClient 是Feign提供的註解,用於通知Feign組件對該接口進行代理(不須要編寫接口實現),使用者可直接經過@Autowired注入。
@RequestMapping 是Spring提供的註解,這裏能夠直接使用之前使用SpringMVC時用過的各類註解,惟一不一樣的是,這裏只是把註解用在了接口上。

若是將Feign與Eureka組合使用,@FeignClient(name = "xapi")意爲通知Feign在調用該接口方法時要向Eureka中查詢名爲 xapi 的服務,從而獲得服務URL,

可是遠程的http接口並非咱們本身的,咱們沒法把它註冊到Eureka中,因此這裏咱們就使用 url = "${url.xapi}" 把要調用的接口的url域名部分直接寫死到配置文件中。

下面就開始調用吧:

Service部分:

/**
 * Created by SYJ on 2017/4/26.
 */
@Service public class InterviewServiceImpl implements InterviewService {

    @Autowired private ResumeClient resumeClient;

    @Override public ResultModel sendInterviewRD(FeedBackDto feedBackDto) {
        return resumeClient.sendInterviewRD(feedBackDto);
    }
}

Controller部分:

/**
 * Created by SYJ on 2017/4/25.
 */
@Controller
@RequestMapping(value = "/interview", produces = {"application/json;charset=UTF-8"})
public class InterviewController extends BaseController {

    @Autowired private InterviewService interviewService;

    /**
     * Created by SYJ on 2017/4/25.
     * @param request
     * @param invitationVo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/sendinterview", produces = {"application/json;charset=UTF-8"})
    @ResponseBody public ResultModel sendInterview(HttpServletRequest request, @RequestBody InvitationVo invitationVo) {
        return interviewService.sendInterviewRD(feedBackDto);
    }
}

 

若是以爲本文對您有幫助,不妨掃描下方微信二維碼打賞點,您的鼓勵是我前進最大的動力:

相關文章
相關標籤/搜索