在SpringBoot应用中,发送Http通常我们使用RestTemplate,但有部分组件底层是使用OkHttp进行Http的操作,而且OKHttp也是一个很优秀的HTTP组件。

RestTempate的springboot封装参考:https://www.cnblogs.com/yangzhilong/p/6640207.html

application.yml

okhttp:
connect-timeout-ms:
keep-alive-duration-sec:
max-idle:
read-timeout-ms:
write-timeout-ms:

Configuration:

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated; import com.longge.gateway.util.OkHttpUtils; import lombok.Getter;
import lombok.Setter;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient; /**
* @author roger yang
* @date 9/16/2019
*/
public class OkHttpConfiguration {
@Resource
private OkHttpConfig okHttpConfig; @Bean
public OkHttpClient okHttpClient() {
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(okHttpConfig.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
.readTimeout(okHttpConfig.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
.writeTimeout(okHttpConfig.getWriteTimeoutMs(),TimeUnit.MILLISECONDS)
.build(); OkHttpUtils.setOkHttpClient(client);
return client;
} @Bean
public ConnectionPool pool() {
return new ConnectionPool(okHttpConfig.getMaxIdle(), okHttpConfig.getKeepAliveDurationSec(), TimeUnit.SECONDS);
} @Component
@ConfigurationProperties(prefix = "okhttp")
@Getter
@Setter
@Validated
static class OkHttpConfig {
@NotNull
private Long connectTimeoutMs;
@NotNull
private Long readTimeoutMs;
@NotNull
private Long writeTimeoutMs;
@NotNull
private Integer maxIdle;
@NotNull
private Long keepAliveDurationSec;
}
}

Util帮助类:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Objects; import com.alibaba.fastjson.JSONObject; import lombok.NonNull;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response; /**
* 参数中Callback表示发送异步请求
* @author roger yang
* @date 9/16/2019
*/
public class OkHttpUtils {
private static OkHttpClient okHttpClient; public static void setOkHttpClient(OkHttpClient client) {
okHttpClient = client;
} /**
* GET Method begin---------------------------------
*/ public static <T> T get(@NonNull String url, Class<T> clasz) {
return get(url, null, null, clasz);
} public static void get(@NonNull String url, Callback callback) {
get(url, null, null, callback);
} public static <T> T get(@NonNull String url, Map<String, String> queryParameter, Class<T> clasz) {
return get(url, null, queryParameter, clasz);
} public static void get(@NonNull String url, Map<String, String> queryParameter, Callback callback) {
get(url, null, queryParameter, callback);
} public static <T> T get(@NonNull String url, Map<String, String> headerParameter, Map<String, String> queryParameter, Class<T> clasz) {
Request request = processGetParameter(url, headerParameter, queryParameter); try (Response resp = okHttpClient.newCall(request).execute();) {
return processResponse(resp, clasz);
} catch (Exception e) {
throw new RuntimeException(e);
}
} public static void get(@NonNull String url, Map<String, String> headerParameter, Map<String, String> queryParameter, Callback callback) {
Request request = processGetParameter(url, headerParameter, queryParameter);
okHttpClient.newCall(request).enqueue(callback);
} private static Request processGetParameter(String url, Map<String, String> headerParameter, Map<String, String> queryParameter) {
Request.Builder builder = new Request.Builder();
if (!isEmptyMap(headerParameter)) {
builder.headers(Headers.of(headerParameter));
}
if (isEmptyMap(queryParameter)) {
builder.url(url);
} else {
boolean hasQuery = false;
try {
hasQuery = new URL(url).getQuery().isEmpty();
} catch (MalformedURLException e) {
throw new RuntimeException("url is illegal");
}
StringBuilder sb = new StringBuilder(url);
if (!hasQuery) {
sb.append("?1=1");
}
queryParameter.forEach((k, v) -> {
sb.append("&").append(k).append("=").append(v);
});
builder.url(sb.toString());
}
return builder.build();
} /**
* POST Method With JSON begin---------------------------------
*/ public static <T> T postJson(@NonNull String url, Class<T> clasz) {
return postJson(url, null, null, clasz);
} public static void postJson(@NonNull String url, Callback callback) {
postJson(url, null, null, callback);
} public static <T> T postJson(@NonNull String url, Map<String, String> headerParameter, Class<T> clasz) {
return postJson(url, headerParameter, null, clasz);
} public static void postJson(@NonNull String url, Map<String, String> headerParameter, Callback callback) {
postJson(url, headerParameter, null, callback);
} public static <T> T postJson(@NonNull String url, Map<String, String> headerParameter, Object bodyObj, Class<T> clasz) {
Request request = processPostJsonParameter(url, headerParameter, bodyObj);
try (Response resp = okHttpClient.newCall(request).execute();) {
return processResponse(resp, clasz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void postJson(@NonNull String url, Map<String, String> headerParameter, Object bodyObj, Callback callback) {
Request request = processPostJsonParameter(url, headerParameter, bodyObj);
okHttpClient.newCall(request).enqueue(callback);
} private static Request processPostJsonParameter(String url, Map<String, String> headerParameter, Object bodyObj) {
Request.Builder builder = new Request.Builder().url(url);
if(!Objects.isNull(bodyObj)) {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONObject.toJSONString(bodyObj));
builder.post(body);
} else {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{}");
builder.post(body);
}
if (!isEmptyMap(headerParameter)) {
builder.headers(Headers.of(headerParameter));
}
return builder.build();
} /**
* POST Method With Form begin---------------------------------
*/ public static <T> T postForm(@NonNull String url, Class<T> clasz) {
return postForm(url, null, null, clasz);
} public static void postForm(@NonNull String url, Callback callback) {
postForm(url, null, null, callback);
} public static <T> T postForm(@NonNull String url, Map<String, String> headerParameter, Class<T> clasz) {
return postForm(url, headerParameter, null, clasz);
} public static void postForm(@NonNull String url, Map<String, String> headerParameter, Callback callback) {
postForm(url, headerParameter, null, callback);
} public static <T> T postForm(@NonNull String url, Map<String, String> headerParameter, Map<String, String> parameters, Class<T> clasz) {
Request request = processPostFormParameter(url, headerParameter, parameters);
try (Response resp = okHttpClient.newCall(request).execute();) {
return processResponse(resp, clasz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void postForm(@NonNull String url, Map<String, String> headerParameter, Map<String, String> parameters, Callback callback) {
Request request = processPostFormParameter(url, headerParameter, parameters);
okHttpClient.newCall(request).enqueue(callback);
} private static Request processPostFormParameter(String url, Map<String, String> headerParameter, Map<String, String> parameters) {
Request.Builder builder = new Request.Builder().url(url);
if(!Objects.isNull(parameters)) {
FormBody.Builder formBuilder = new FormBody.Builder();
parameters.forEach((k, v) -> {
formBuilder.add(k, v);
});
builder.post(formBuilder.build());
}
if (!isEmptyMap(headerParameter)) {
builder.headers(Headers.of(headerParameter));
}
return builder.build();
} @SuppressWarnings("unchecked")
private static <T> T processResponse(Response resp, Class<T> clasz) throws IOException {
if (resp.isSuccessful()) {
if (Objects.equals(Void.class, clasz)) {
return null;
}
String respStr = resp.body().string();
if(Objects.equals(String.class, clasz)) {
return (T)respStr;
}
return JSONObject.parseObject(respStr, clasz);
}
return null;
} private static boolean isEmptyMap(Map<? extends Object, ? extends Object> map) {
return Objects.isNull(map) || map.isEmpty();
}
}

GitHub地址:https://github.com/yangzhilong/new-gateway-test.git

如果想要OkHttp的装配是非自动的,可以采用自定义@EnableXX注解来实现。

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import com.longge.gateway.configuration.OkHttpConfiguration; /**
* @author roger yang
* @date 9/16/2019
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(OkHttpConfiguration.class)
public @interface EnableOkHttp { }

然后把OkHttpConfiguration类的@Configuration注解去掉,当你要用时在启动类加上@EnableOkHttp即可。

springboot装配OkHttp组件的更多相关文章

  1. springboot自动装配(1)---@SpringBootApplication注解怎么自动装配各种组件

    1.对于springboot个人认为它就是整合了各种组件,然后提供对应的自动装配和启动器(starter) 2.@SpringBootApplication注解其实就是组合注解,通过它找到自动装配的注 ...

  2. Spring装配bean--01组件扫描和自动装配

    Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系 Spring提供了三种主要的装配机制: 在XML中进行显式配置 在Java中进行显式配置 隐式的bean发现机制和自动装 ...

  3. 装配SpringBean(四)--注解装配之组件扫描

    前两篇文章我总结了通过XML方式装配bean的实现方式,虽然比较简单,但是需要配置很多,很多时候我们都会使用注解进行装配.使用注解的方式可以减少XML的配置,既能实现XML的功能,还提供了自动装配功能 ...

  4. 【Spring】装配Bean 组件扫描

    实现自动装配需要用注解:注解分为 spring规范和java规范 ,java规范需要引入javax.inject 包 ,使用maven,直接引入. 从中可以看到 @Named @Inject属于jav ...

  5. springboot添加swagger2组件

    swagger2是一个可以构建和调试RESTful API文档的组件,利用swagger2的注解可以快速的在项目中构建Api文档,并且提供了测试API的功能 1,引入依赖 <dependency ...

  6. 一步步从Spring Framework装配掌握SpringBoot自动装配

    目录 Spring Framework模式注解 Spring Framework@Enable模块装配 Spring Framework条件装配 SpringBoot 自动装配 本章总结 Spring ...

  7. Spring Boot之从Spring Framework装配掌握SpringBoot自动装配

    Spring Framework模式注解 模式注解是一种用于声明在应用中扮演“组件”角色的注解.如 Spring Framework 中的 @Repository 标注在任何类上 ,用于扮演仓储角色的 ...

  8. SpringBoot | 2.1 SpringBoot自动装配原理

    @ 目录 前言 1. 引入配置文件与配置绑定 @ImportResource @ConfigurationProperties 1.1 @ConfigurationProperties + @Enab ...

  9. 浅尝Spring注解开发_自定义注册组件、属性赋值、自动装配

    Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含自定义扫描组件.自定义导入组件.手动注册组件.自动注入方法和参数.使用Spring容器底层组件等 配置 @Confi ...

随机推荐

  1. input限制输入

    input 只能输入数字.字母.汉字等   1.文本框只能输入数字代码(小数点也不能输入) <input onkeyup="this.value=this.value.replace( ...

  2. 【前端_js】array.forEach和$.each()及$().each()的用法与区别

    1.$.each():方法是jQuery中的方法,用于遍历数组或对象.用法:$.each(array,function(index,value){...}),有两个参数,第一个为待遍历的数组或对象,第 ...

  3. z = z*z + c的分型图如何画

    使用python的图形库. 环境:conda+jupyter notebook 代码如下: import numpy as np from PIL import Image from numba im ...

  4. docker建镜像

    docker建镜像 # build docker build -t $(BASE):$(TAG) -f run.docker . Dockerfile Dockerfile是自定义镜像的一个重要帮手, ...

  5. Django知识点归纳总结之HTTP协议与URL

    Django复习知识点归纳总结 1.HTTP协议 ​ 超文本传输协议(Hyper Text Transfer Protocol),是用于万维网服务器与本地浏览器之间的传输超文本的传送协议. ​ HTT ...

  6. SQL血的教训

    1.    每次查询的数据要有限制     2013年1月  产品独立数据库,由于多条SQL每次查询数据超过几千条,有些超过10万条数据未分页,造成应用服务器CPU有时持续100%. 2.    禁止 ...

  7. 点击一个超链接,弹出固定大小的新窗口(js实现)

    1.最基本的弹出窗口代码 <SCRIPT LANGUAGE="javascript"> <!-- window.open ('page.html') --> ...

  8. Monkey面试整理

    1. 查找进程命令是什么? adb shell ps adb shell ps |findstr 名称 2. 如何获取包名 1)获取手机上的所有包名信息. adb shell pm list pack ...

  9. sqoop2的相关配置,启动,停止命令(转)

    原博客地址:http://blog.csdn.net/u012772782/article/details/52949181 sqoop2配置: 一.添加sqoop2到系统环境变量中: export ...

  10. Collections.synchronizedList使用

    1.SynchronizedList类具体代码: static class SynchronizedList<E> extends SynchronizedCollection<E& ...