使用Spring Cloud Feign作為HTTP客戶端調用遠程HTTP服務


如果你的項目使用了SpringCloud微服務技術,那么你就可以使用Feign來作為http客戶端來調用遠程的http服務。當然,如果你不想使用Feign作為http客戶端,也可以使用比如JDK原生的URLConnection、Apache的Http Client、Netty的異步HTTP Client或者Spring的RestTemplate。

 

那么,為什么我們要使用Feign呢?

首先我們的項目使用了SpringCloud技術,而Feign可以和SpringCloud技術無縫整合。並且,你一旦使用了Feign作為http客戶端,調用遠程的http接口就會變得像調用本地方法一樣簡單。

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

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

gradle依賴:

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

Maven依賴:

<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)聲明要調用的遠程接口

/**
 * 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);
}

說明:

@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);
    }
}

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM