1. 程式人生 > >使用Spring Cloud Feign作為HTTP客戶端調用遠程HTTP服務

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

技術 private 最大的 alt face class extends 使用 依賴

如果你的項目使用了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);
    }
}

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

技術分享

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