springboot装配OkHttp组件
在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组件的更多相关文章
- springboot自动装配(1)---@SpringBootApplication注解怎么自动装配各种组件
1.对于springboot个人认为它就是整合了各种组件,然后提供对应的自动装配和启动器(starter) 2.@SpringBootApplication注解其实就是组合注解,通过它找到自动装配的注 ...
- Spring装配bean--01组件扫描和自动装配
Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系 Spring提供了三种主要的装配机制: 在XML中进行显式配置 在Java中进行显式配置 隐式的bean发现机制和自动装 ...
- 装配SpringBean(四)--注解装配之组件扫描
前两篇文章我总结了通过XML方式装配bean的实现方式,虽然比较简单,但是需要配置很多,很多时候我们都会使用注解进行装配.使用注解的方式可以减少XML的配置,既能实现XML的功能,还提供了自动装配功能 ...
- 【Spring】装配Bean 组件扫描
实现自动装配需要用注解:注解分为 spring规范和java规范 ,java规范需要引入javax.inject 包 ,使用maven,直接引入. 从中可以看到 @Named @Inject属于jav ...
- springboot添加swagger2组件
swagger2是一个可以构建和调试RESTful API文档的组件,利用swagger2的注解可以快速的在项目中构建Api文档,并且提供了测试API的功能 1,引入依赖 <dependency ...
- 一步步从Spring Framework装配掌握SpringBoot自动装配
目录 Spring Framework模式注解 Spring Framework@Enable模块装配 Spring Framework条件装配 SpringBoot 自动装配 本章总结 Spring ...
- Spring Boot之从Spring Framework装配掌握SpringBoot自动装配
Spring Framework模式注解 模式注解是一种用于声明在应用中扮演“组件”角色的注解.如 Spring Framework 中的 @Repository 标注在任何类上 ,用于扮演仓储角色的 ...
- SpringBoot | 2.1 SpringBoot自动装配原理
@ 目录 前言 1. 引入配置文件与配置绑定 @ImportResource @ConfigurationProperties 1.1 @ConfigurationProperties + @Enab ...
- 浅尝Spring注解开发_自定义注册组件、属性赋值、自动装配
Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含自定义扫描组件.自定义导入组件.手动注册组件.自动注入方法和参数.使用Spring容器底层组件等 配置 @Confi ...
随机推荐
- Golang: 并发抓取网页内容
在上一篇中,我们根据命令行的 URL 参数输入,抓取对应的网页内容并保存到本地磁盘,今天来记录一下如何利用并发,来抓取多个站点的网页内容. 首先,我们在上一次代码的基础上稍作改造,使它能够获取多个站点 ...
- jQuery遍历之find()
/**案例说明: *首先理清楚find()函数同children()函数之间的区别 * 1. find()会遍历给定节点下的所有的元素节点. * 2. children()之后遍历给定节点下的单一层级 ...
- Django 之 Form 组件
常用功能 From 组件主要有以下几大功能: 生成 HTML 标签 验证用户数据(显示错误信息) HTML Form 提交保留上次提交数据 初始化页面显示内容 小试牛刀 下面我们通过 Form 组件来 ...
- ARM架构体系
架构 处理器家族 ARMv1 ARM1 ARMv2 ARM2.ARM3 ARMv3 ARM6, ARM7 ARMv4 StrongARM.ARM7TDMI.ARM9TDMI ARMv5 ARM7EJ. ...
- Mac Docker安装Redis4.0
mkdir redis 在~目录下创建redis目录 docker run -d -p 6379:6379 -v $PWD/redis:/data -d --name redis4.0 redis:4 ...
- PAT 乙级 1004.成绩排名 C++/Java
1004 成绩排名 (20 分) 题目来源 读入 n(>)名学生的姓名.学号.成绩,分别输出成绩最高和成绩最低学生的姓名和学号. 输入格式: 每个测试输入包含 1 个测试用例,格式为 第 1 行 ...
- 算法——dfs 判断是否为BST
95. 验证二叉查找树 中文English 给定一个二叉树,判断它是否是合法的二叉查找树(BST) 一棵BST定义为: 节点的左子树中的值要严格小于该节点的值. 节点的右子树中的值要严格大于该节点的值 ...
- Find the median(2019年牛客多校第七场E题+左闭右开线段树)
题目链接 传送门 题意 每次往集合里面添加一段连续区间的数,然后询问当前集合内的中位数. 思路 思路很好想,但是卡内存. 当时写的动态开点线段树没卡过去,赛后机房大佬用动态开点过了,\(tql\). ...
- CString写的web server
socket通信机制 文件加载机制 手抄代码 test\\2017
- JavaScript数组常用操作方法
ES5操作数组的方法 1.concat() concat() 方法用于连接两个或多个数组.该方法不会改变现有的数组,仅会返回被连接数组的一个副本. var arr1 = [1,2,3]; var ar ...