Spring Cloud Feign优化为什么要用HttpClient替换URLConnection?

看到很多谈Feign优化的文章都提到要将默认的URLConnection替换为HttpClient,比如这篇文章:Spring Cloud Feign…
关注者
4
被浏览
2,624

2 个回答

“URLConnection是长连接,也就是可以并发发送多个请求的”--------每个请求也是串行的,不是并发的。

如果你的项目使用了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"

1.

Maven依赖:


<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-netflix-core</artifactId>

<version>1.3.2.RELEASE</version>

</dependency>


(2)在properties配置文件中配置要调用的接口的URL路径(域名部分)


url.api=api.framwok.com



(2)声明要调用的远程接口


FeignClient(name = "api", url = "${url.api}")

@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注入。

1.

@RequestMapping 是Spring提供的注解,这里可以直接使用以前使用SpringMVC时用过的各种注解,唯一不同的是,这里只是把注解用在了接口上。


如果将Feign与Eureka组合使用,@FeignClient(name = "api")意为通知Feign在调用该接口方法时要向Eureka中查询名为 api 的服务,从而得到服务URL,


但是远程的http接口并不是我们自己的,我们无法把它注册到Eureka中,所以这里我们就使用 url = "${url.api}" 把要调用的接口的url域名部分直接写死到配置文件中。


下面就开始调用吧:


Service部分:


/**

*/Service

public class InterviewServiceImpl implementsAutowired

privateresumeClient;

Override

publicsendInterviewRD(FeedBackDto feedBackDto) {

return resumeClient.sendInterviewRD(feedBackDto);

}

}


Controller部分:


@Controller

@RequestMapping(value = "/interview", produces = {"application/json;charset=UTF-8"})

public class InterviewController extendsAutowired

privateinterviewService;


/**

* 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

publicsendInterview(HttpServletRequest request, @RequestBodyreturn interviewService.sendInterviewRD(feedBackDto);

}

}

Spring Cloud微服务架构实战派  微服务架构设计开发运维部署 Java架构师书籍