一.httpclient方式:
httpclient是apache下的一个子项目,引入依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
用法:
- 创建httpclient对象
- 构建请求对象post,get请求
- 如果有参数,就去构造请求参数
3.1.使用uribuilder去构造请求参数
3.2.构建表单实体:把表单实体放入到post请求对象中
4.执行请求,并接收响应
5.处理响应结果
连接池:因为频繁的打开和关闭连接,效率降低,因此使用连接管理器。
注意不要关闭连接,不然会销毁连接池:
定期关闭无效连接:
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// 设置最大连接数
cm.setMaxTotal(200);
// 设置每个主机地址的并发数
cm.setDefaultMaxPerRoute(20);
new IdleConnectionEvictor(cm).start();
}
public static class IdleConnectionEvictor extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
设置请求参数:
二.dubbo调用(RPC调用方式):
开发学习文档:http://dubbo.io/Developer+Guide-zh.htm
导入zookeeper注册中心:
启动zookeeper服务,将服务发布到dubbo中,需要配置dubbo的配置文件(服务端)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="dubbo-sso-query-server" />
<!-- 这里使用的注册中心是zookeeper -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" client="zkclient"/>
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 将该接口暴露到dubbo中 -->
<dubbo:service interface="com.taotao.sso.query.api.UserQueryService " ref="userQueryServiceImpl" />
<!-- 将具体的实现类加入到Spring容器中 -->
<bean id="userQueryServiceImpl" class="com.taotao.sso.query.service.UserQueryServiceImpl" />
</beans>
然后需要在web.xml中引入扫描dubbo的配置文件:
加入dubbo的依赖:
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.5.3</version>
<exclusions>
<exclusion>
<!-- 排除传递spring依赖 -->
<artifactId>spring</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
然后配置dubbo调用方(消费者方):dubbo-consumer.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="taotao-web-consumer" />
<!-- 这里使用的注册中心是zookeeper -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" client="zkclient"/>
<!-- 从注册中心中查找服务 -->
<dubbo:reference id="userQueryService" interface="com.taotao.sso.query.api.UserQueryService"/>
<!--registry: 指在注册中心自动寻找监控服务 -->
<dubbo:monitor protocol="registry"/>
</beans>
同样需要配置扫描在web.xml中
启动dubbo-admin.jar ,这是一个dubbo管理控制台项目
下载链接:http://download.csdn.net/download/mappingsunlight/9489736
启动后,可通过url来访问,就可以看到用户界面,可以查看服务的调用情况等信息。
三.feign的调用:(底层是httpclient,可配置连接池,超时时间,更高级的服务订阅,负载均衡和断路器)
API:通过注解@RequestLine来配置调用方式和调用地址
SDK:通过@value注解获取容器中的配置的值,通过@Bean注解来返回对应的API
例如:
Api:
@RequestLine("POST /mimosa/boot/investor/baseaccount/syncUserName?uid={uid}&name={name}&idNum={idNum}")
public Response syncUserName(@Param("uid") String uid,
@Param("name") String name,
@Param("idNum") String idNum);
Sdk:
@Value("${money.url:localhost}")
private String host;
@Bean
public MoneyAppApi createMoneySdk() {
return Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Logger.JavaLogger().appendToFile("money.log")).logLevel(Logger.Level.FULL)
.target(MoneyAppApi.class, "http://" + this.host + "/");
}
至此,接口调用方式完成。
四. RestTemplate的调用:
RestTemplate调用也是基于http,可设置超时时间(连接超时时间和文件下载超时时间)
例如:(设置了20秒的连接超时和20秒的下载超时)
HttpEntity<Object> httpEntity = new HttpEntity<>(fieldId);
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
//连接时间和超时下载时间
requestFactory.setConnectTimeout(20*1000);
requestFactory.setReadTimeout(20*1000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
ResponseEntity<String> responseEntity = restTemplate.exchange(getFilePathUrl, HttpMethod.POST, httpEntity, String.class);
HttpStatus httpStatus = responseEntity.getStatusCode();
String body = responseEntity.getBody();
if (httpStatus.equals(HttpStatus.OK)) {
JSONObject jsonContentEx = JSONObject.fromString(body);
filePaths = jsonContentEx.getString("filePaths");
}
当然RestTemplate也区分get和post请求方式:
get请求:
String result = restTemplate.getForObject(sb.toString(), String.class, new String[] {});
post请求:
UserInfoVo result = restTemplate.postForObject(url, req, UserInfoVo.class);
可根据自己的需要来决定使用那种方式:
exchange的话需要解析返回的header和body。
get和post可指定返回的实体。