使用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);
    }
}
复制代码
原文地址:https://www.cnblogs.com/jiangzhaowei/p/9880933.html