在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. openssl生成证书及签名

    第一步,生成私钥 $ openssl genrsa -out privatekey.pem 2048 查看生成的私钥内容 $ file privatekey.pem privatekey.pem: P ...

  2. Nexus安装和使用

    1.前言 最近项目需要搭建maven私服,方便管理后期团队成员使用上传自己的包,因此决定使用nexus来搭建私服,搭建好的nexus地址. 2.准备工作 阿里云服务器ECS一台 1核CPU 2G内存( ...

  3. 【异常】[ERROR] The cloud assistant is not installed on the ECS, or the cloud assistant is unavailable. cloudassistant is uninstall

    一.异常信息 [INFO] Deployment File is Uploading... [INFO] IDE Version:IntelliJ IDEA [INFO] Alibaba Cloud ...

  4. 百度云人脸识别API人脸库管理

      from urllib import request import base64 import requests import re import json import urllib impor ...

  5. python-Arduino串口传输数据到电脑并保存至excel表格

    起因:学校运河杯报了个项目,制作一个天气预测的装置.我用arduino跑了BME280模块,用蓝牙模块实现两块arduino主从机透传.但是为了分析,还需要提取出数据.因此我用python写了个上位机 ...

  6. VMware虚拟化kvm安装部署总结

    虚拟化 1.环境 Centos7.3 关闭selinux,关闭防火墙 2.虚拟化环境配置 2.1 kvm部署安装 1. VMware 配置桥接模式 2.bios开启虚拟机,以本地台式机为例, 重启动电 ...

  7. VS Code + MinGW + Clang + OpenGL (vscode 配置 opengl环境)

    vscode配置opengl环境会遇到一些问题,这里是在看了一些博文之后给出的一篇完整的可行的配置 首先,要配置C++环境,网上有很多完整的配置C++环境的教程,这里就引用一条 https://www ...

  8. 算法 翻转二叉树 dfs

    翻转二叉树 翻转一棵二叉树.左右子树交换. Example 样例 1: 输入: {1,3,#} 输出: {1,#,3} 解释: 1 1 / => \ 3 3 样例 2: 输入: {1,2,3,# ...

  9. springboot-注解-@Repository、@Service、@Controller 和 @Component

    Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository.@Service 和 @Controller.在目前的 Spring ...

  10. loj10017. 「一本通 1.2 练习 4」传送带(三分套三分)

    题目描述 在一个2维平面上有两条传送带,每一条传送带可以看成是一条线段.两条传送带分别为线段AB和线段CD.lxhgww在AB上的移动速度为P,在CD上的移动速度为Q,在平面上的移动速度R.现在lxh ...