当前位置: 首页 > news >正文

Android OkHttp源码阅读详解一

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家
👉点击跳转到教程

前言:源码阅读基于okhttp:3.10.0

Android中OkHttp源码阅读二(责任链模式)

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

1、首先回顾OkHttp的使用

public class MainActivity extends RxActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/*** OkHttp的使用*/private static void okHttpUseAction() {//通过构建者设计模式得到OkHttpClientOkHttpClient okHttpClient = new OkHttpClient.Builder().build();//get请求 构建者模式拿到requestRequest request = new Request.Builder().url("https://www.baidu.com/").get().build();//Call  call = RealCallCall call = okHttpClient.newCall(request);
//        call.cancel();//取消请求//同步方法,我们需要自己开启子线程 耗时
//        try {
//            Response response = call.execute();
//            String string = response.body().string();
//            InputStream inputStream = response.body().byteStream();
//            Reader reader = response.body().charStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }//异步方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {System.out.println("请求失败...");}@Overridepublic void onResponse(Call call, Response response) throws IOException {String string = response.body().string();System.out.println("请求完成:" + string);
//                InputStream inputStream = response.body().byteStream();
//                Reader reader = response.body().charStream();}});}public static void main(String[] args) {okHttpUseAction();}
}

2、OkHttp源码阅读之线程池详解

/*** @Author: ly* @Date: 2023/9/3* @Description: 线程池的使用*/
public class MyThreadPool {public static void main(String[] args) {//比较耗性能,开启子线程,然后回收new Thread() {@Overridepublic void run() {super.run();}}.start();//java 1.5 线程如何复用  线程池复用//子线程//需要一份工作:招聘工作,员工完成工作后,解聘//需要一份工作:招聘工作,员工完成工作后,解聘//需要一份工作:招聘工作,员工完成工作后,解聘//线程池相当于以下//需要一份工作:招聘工作,员工完成工作后,继续执行其他工作,解雇//java 1.5 线程池复用,线程池(线程,如何让这么多线程复用,线程管理工作)//Executor//    --ExecutorService//        --AbstractExecutorService//          --ThreadPoolExecutor//ThreadPoolExecutor 学习此类//线程池里面,只有一个核心线程在跑任务/*** corePoolSize:核心线程数* maximumPoolSize:线程池非核心线程数,线程池规定大小* keepAliveTime:时间数值* unit:时间单位*       参数三和四作用:正在执行的任务Runnable 20 大于核心线程数  参数三和参数四才会起作用*       作用:Runnable1执行完毕后闲置60s,如果过了闲置60s,会回收掉Runnable1,如果在闲置时间60s内,复用此线程Runnable1* workQueue:队列*            作用:会把超出的任务加入到队列中,缓存起来*/
//        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());//Exception in thread "main" java.lang.IllegalArgumentException  会崩溃
//        ExecutorService executorService = new ThreadPoolExecutor(5,
//                1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());//        ExecutorService executorService = new ThreadPoolExecutor(5,
//                10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());//想实现缓存,线程池方案/*** corePoolSize:核心线程数* maximumPoolSize:最大线程数。线程池非核心线程数,线程池规定大小* keepAliveTime:时间数值* unit:时间单位*       参数三和四作用:正在执行的任务Runnable 20 大于核心线程数  参数三和参数四才会起作用*       作用:Runnable1执行完毕后闲置60s,如果过了闲置60s,会回收掉Runnable1,如果在闲置时间60s内,复用此线程Runnable1* workQueue:队列*            作用:会把超出的任务加入到队列中,缓存起来*/
//        ExecutorService executorService = new ThreadPoolExecutor(0,
//                Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());ExecutorService executorService = new ThreadPoolExecutor(0,Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(),new ThreadFactory() {@Overridepublic Thread newThread(Runnable r) {Thread thread = new Thread();thread.setName("MyOkHttp Dispatcher");thread.setDaemon(false);//不是守护线程return thread;}});for (int i = 0; i < 20; i++) { //循环第二次,闲置60s,复用上一次任务executorService.execute(new Runnable() {@Overridepublic void run() {try {Thread.sleep(1000);System.out.println("当前线程,执行耗时任务,线程是:" + Thread.currentThread().getName());} catch (InterruptedException e) {e.printStackTrace();}}});}/**************************************JAVA提供了API***********************************************///Java设计者考虑到了不用使用线程池的参数配置,提供了APIExecutorService executorService1 = Executors.newCachedThreadPool();executorService1.execute(new Runnable() {@Overridepublic void run() {}});//线程池里面只有一个核心线程,最大线程也只有一个ExecutorService executorService2 = Executors.newSingleThreadExecutor();Executors.newFixedThreadPool(5); //指定固定大小线程池}
}

3、守护线程详解

/*** @Author: ly* @Date: 2023/9/3* @Description: 守护线程的使用*/
public class MyThread {public static void main(String[] args) {Thread thread = new Thread() {@Overridepublic void run() {super.run();while (true) {
//                    try {
//                        Thread.sleep(10);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    } finally {
//                        System.out.println("run...");
//                    }System.out.println("run...");}}};//守护线程thread.setDaemon(true);thread.start();//JVM main()所持有的进程该结束了try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}
}

4、根据OkHttp中构建者模式写一个例子
1.定义一个类HomeParam

/*** @Author: ly* @Date: 2023/9/3* @Description: 房子的图纸*/
public class HomeParam {private double width;private double height;private String color = "白色";public HomeParam() {}public HomeParam(double width, double height, String color) {this.width = width;this.height = height;this.color = color;}public double getWidth() {return width;}public void setWidth(double width) {this.width = width;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}@Overridepublic String toString() {return "画出来的图纸:HomeParam{" +"width=" + width +", height=" + height +", color='" + color + '\'' +'}';}
}

2.定义一个类House

/*** @Author: ly* @Date: 2023/9/3* @Description: 真实存在的房子*/
public class House {private double width;private double height;private String color;public House() {}public House(double width, double height, String color) {this.width = width;this.height = height;this.color = color;}public double getWidth() {return width;}public void setWidth(double width) {this.width = width;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}@Overridepublic String toString() {return "具体建造出来的房子:House{" +"width=" + width +", height=" + height +", color='" + color + '\'' +'}';}
}

3、定义一个类Worker

/*** @Author: ly* @Date: 2023/9/3* @Description: 工人开始建造房子*/
public class Worker {//拿到图纸private HomeParam mHomeParam;public void setHomeParam(HomeParam homeParam) {mHomeParam = homeParam;}//工作,盖房子public House buildHouse() {House house = new House();house.setHeight(mHomeParam.getHeight());house.setWidth(mHomeParam.getWidth());house.setColor(mHomeParam.getColor());return house;}
}

4、定义一个类DesignerPerson

/*** @Author: ly* @Date: 2023/9/3* @Description: 设计师*/
public class DesignerPerson {private HomeParam mHomeParam;private Worker mWorker;public DesignerPerson() {mHomeParam = new HomeParam();mWorker = new Worker();}/*** 增加楼层** @param height 高度*/public DesignerPerson addHeight(double height) {mHomeParam.setHeight(height);return this;}/*** 增加宽度** @param width 宽度*/public DesignerPerson addWidth(double width) {mHomeParam.setWidth(width);return this;}/*** 增加颜色** @param color 颜色*/public DesignerPerson addColor(String color) {mHomeParam.setColor(color);return this;}/*** 把图纸给工人* 员工说房子盖好了** @return*/public House build() {mWorker.setHomeParam(mHomeParam);return mWorker.buildHouse();}
}

5.定义一个类UserClient

/*** @Author: ly* @Date: 2023/9/3* @Description: 用户有一个需求盖房子*/
public class UserClient {
//    public static void main(String[] args) {//第一版//找到建筑公司
//        DesignerPerson designerPerson = new DesignerPerson();
//        designerPerson.addHeight(4);
//        designerPerson.addWidth(120.0);
//        designerPerson.addColor("绿色");
//
//        designerPerson.addHeight(2);
//        designerPerson.addWidth(100.0);
//        designerPerson.addColor("红色");
//
//        designerPerson.addHeight(3);
//        designerPerson.addWidth(90.0);
//        designerPerson.addColor("黄色");
//
//        //复制的过程
//
//        House house = designerPerson.build();
//        System.out.println(house);
//    }public static void main(String[] args) {//第二版,链式调用House house = new DesignerPerson().addColor("白色").addWidth(100).addHeight(8).build();System.out.println(house);}
}

2、OkHttp主线流程源码阅读

1.OSI七层模型,TCP/IP模型(四层),HTTP格式OSI七层参考模型  --> TCP/IP参考模型TCP/IP参考模型四层:应用层 --> HTTP,HTTPS传输层 --> SocketHTTP get(请求行,请求属性集) post(请求行,请求属性集,type(form表单提交,还是其他提交),len(长度)==请求体)2.OkHttp源码的主线流程
OkHttp的使用OkHttpClient 通过构建者设计模式得到OkHttpClient
Request  通过构建者设计模式得到Request
Call  实际得到的是final class RealCall implements Call
//异步方法
call.enqueue(new Callback()
//不能执行大于1次 enqueue 否则会抛出异常Exception in thread "main" java.lang.IllegalStateException: Already Executed
synchronized (this) {if (executed) throw new IllegalStateException("Already Executed");executed = true;}
//拿到调度器dispatcher执行enqueue()方法
client.dispatcher().enqueue(new AsyncCall(responseCallback));Dispatcher{/** Ready async calls in the order they'll be run. */  等待队列private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();运行的队列/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();//最终会调用到Dispatcher类中的enqueue()方法synchronized void enqueue(AsyncCall call) {//同时运行的异步任务小于64&&同时访问(同一个)的服务器,不能超过5个  条件满足加入到运行队列中,然后执行if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {runningAsyncCalls.add(call);executorService().execute(call); //执行} else {//加入到等待队列readyAsyncCalls.add(call);}}Deque双端队列:Deque(双端队列)是一种用于管理HTTP请求和响应拦截器的数据结构。Deque是"Double-ended Queue"的缩写,表示它可以在两端进行元素的插入和删除操作。AsyncCall 执行耗时任务signalledCallback 为true:这个错误是用户造成的,和OkHttp没有关系为false:这个错误是OkHttp造成的。 onFailure}梳理主线流程:
OkHttpClient --> Request -> newCall  RealCall.enqueue(){不能重复执行} --> Dispatcher.enqueue(AsyncCall)-->
Dispatcher{if:先加入运行队列里面去,执行异步任务 else 直接加入等待队列} --> 异步任务 AsyncCall.execute()分析OkHttp里面的线程池
executorService().execute(call);public synchronized ExecutorService executorService() {if (executorService == null) {executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));}return executorService;
}
分析结果:OkHttp里面的线程池,采用的是缓存方案+线程工厂 name  不是守护线程
总结:采用的是缓存方案+定义线程工程(设置线程名,设置不是守护线程)
缓存方案:参数1 == 0参数2 == Integer.MAX_VALUE参数3 == 60s闲置时间,只要Runnable > 大于参数1  起作用(60s 之内就会复用之前的任务,60s之内就会回收任务)--------------------------------->
看OkHttp源码,发现OkHttp里面使用了构建者设计模式,所以才要学习构建者设计模式
OkHttpClient ---构建者模式
Request      ---构建者模式
开始学习构建者设计模式 -->盖房子的例子(根据OkHttp源码中的链式调用优化)

相关文章:

Android OkHttp源码阅读详解一

博主前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住也分享一下给大家 &#x1f449;点击跳转到教程 前言&#xff1a;源码阅读基于okhttp:3.10.0 Android中OkHttp源码阅读二(责任链模式) implementation com.squareup.o…...

UG\NX CAM二次开发 查询工序所在的方法组TAG UF_OPER_ask_method_group

文章作者:代工 来源网站:NX CAM二次开发专栏 简介: UG\NX CAM二次开发 查询工序所在的方法组TAG UF_OPER_ask_method_group 效果: 代码: void MyClass::do_it() { int count=0;tag_t * objects;UF_UI_ONT_ask_selected_nodes(&count, &objects);for (i…...

npm获取函数名称和测试js脚本

这边遇到一个类似于测试的需求&#xff0c;需要从一个js文件里获取函数名&#xff0c;然后尝试执行这些函数和创建实例。这边首先遇到了一个问题是如何动态获取js里的函数名和类名&#xff0c;我这边暂时没找到特别好的方法&#xff0c;已有的方法都是类似于提取语法树那种提取…...

ISO/IEC/ITU标准如何快速查找(三十九)

简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长! 优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀 人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药. 更多原创,欢迎关注:Android…...

git私房菜

文章目录 1、公司项目开发Git协作流程2、合并相关的操作3、Git常用命令总结 公司中如何使用Git协同开发的&#xff1f;本文将具体介绍开发模式&#xff0c;以及一些常用命令。 1、公司项目开发Git协作流程 公司一个完整的项目出来&#xff0c;项目的推进是在主分支master上进行…...

docker安装grafana,prometheus,exporter以及springboot整合详细教程(GPE)

springboot项目ip:192.168.168.1 测试服务器ip:192.168.168.81 文章来自互联网,自己略微整理下,更容易上手,方便自己,方便大家 最终效果: node springboot 1.下载镜像 docker pull prom/node-exporter docker pull prom/mysqld-exporter docker pull google/cadvisor dock…...

cka/ckad应试指南 从docker到kubernetes完全攻略

《cka/ckad应试指南 从docker到kubernetes完全攻略》 段超飞 docker 1-安装并配置docker&#xff0c;yum源&#xff0c;docker下载慢 2-基本命令&#xff1a;镜像管理&#xff0c;基本命令&#xff0c;创建容器 3-网络&#xff0c;存储卷&#xff0c;镜像仓库&#xff0c; 4-do…...

js中如何使用可选函数参数

js是网络的核心技术之一。大多数网站都使用它&#xff0c;并且所有现代网络浏览器都支持它&#xff0c;而不需要插件。在本文中&#xff0c;我们将讨论不同的提示和技巧&#xff0c;它们将帮助您进行日常 JavaScript 开发。 在 JavaScript 编码中&#xff0c;您经常需要将函数…...

基于Open3D的点云处理17-Open3d的C++版本

参考&#xff1a; http://www.open3d.org/docs/latest/cpp_api.htmlhttp://www.open3d.org/docs/latest/getting_started.html#chttp://www.open3d.org/docs/release/cpp_project.html#cplusplus-example-projecthttps://github.com/isl-org/open3d-cmake-find-packagehttps:/…...

GIT相关内容总结

Git相关内容总结 Git的功能Git常见命令 Git的功能 Git是版本控制工具。版本控制就是记录你对文件做的所有改动的一个系统&#xff0c;包括改动的内容&#xff0c;改动的时间&#xff0c;改动的备注等&#xff0c;便于你恢复特定的版本。 版本控制系统分为本地版本控制系统&…...

golang清空数组的方法

在Go语言中&#xff0c;数组是固定长度的数据结构&#xff0c;无法直接清空。但是&#xff0c;你可以通过以下两种方法来模拟清空数组的效果&#xff1a; 使用切片&#xff08;Slicing&#xff09;&#xff1a; 切片是动态长度的&#xff0c;可以用来清空数组。你可以创建一个…...

postgresql并行查询(高级特性)

######################## 并行查询 postgresql和Oracle一样支持并行查询的,比如select、update、delete大事无开启并行功能后,能够利用多核cpu,从而充分发挥硬件性能,提升大事物的处理效率。 pg在9.6的版本之前是不支持的并行查询的,从9.6开始支持并行查询,但是功能非常…...

Python所有方向的学习路线图!!

学习路线图上面写的是某个方向建议学习和掌握的知识点汇总&#xff0c;举个例子&#xff0c;如果你要学习爬虫&#xff0c;那么你就去学Python爬虫学习路线图上面的知识点&#xff0c;这样学下来之后&#xff0c;你的知识体系是比较全面的&#xff0c;比起在网上找到什么就学什…...

2022年03月 C/C++(七级)真题解析#中国电子学会#全国青少年软件编程等级考试

C/C++编程(1~8级)全部真题・点这里 第1题:红与黑 有一间长方形的房子, 地上铺了红色、 黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上, 只能向相邻的黑色瓷砖移动。 请写一个程序, 计算你总共能够到达多少块黑色的瓷砖。 时间限制: 1000 内存限制: 65536 输入…...

使用 Laf 一周内上线美术狮 AI 绘画小程序

“美术狮 AI 绘画”&#xff08;以下简称“美术狮”&#xff09;&#xff0c;是我们小团队的一次尝试&#xff0c;定位是人人都可以上手的&#xff0c;充满创意的&#xff0c;理解中文和中国文化的图片生成工具。 在完善图像模型和论证核心问题之后&#xff0c;我们开始构建 MV…...

Kubernetes(k8s)当中安装并使用ingress暴露应用

Kubernetes当中安装并使用ingress暴露应用 为什么需要Ingress前期准备集群准备LoadBalancer准备 安装Ingress-Nginx下载地址v1.3.1v1.8.1 修改文件v1.3.1v1.8.1修改ingress服务类型配置 执行安装 部署应用通过ingress-nginx暴露应用部署ingress的yaml文件v1.3.1v1.8.1 为什么需…...

03-Flask-工程配置加载方式

工程配置加载方式 前言配置对象中加载配置文件中加载环境变量中加载三种配置方式优缺点工厂模式创建Flask app 前言 本篇来学习下Flake工程配置加载方式 配置对象中加载 应用场景&#xff1a;作为默认配置写在代码中 # -*- coding: utf-8 -*- # Time : 2023/9/2 # Autho…...

Orangepi安装外设库 wiringPi

注意&#xff1a;mobaXterm传送文件要在SSH登陆环境下才可以。 同时电脑和orangepi都在同一个wifi下。...

[dasctf]misc3 chrchrchr.pcapng

webshell 流量分析 php代码部分没啥看的&#xff0c;主要在标黄的部分&#xff0c;裁剪掉前面的字符可base解码 能看到在向a.txt中写入数据 wp # tshark.exe -r chrchrchr.pcapng -T fields -e urlencoded-form.value -Y "urlencoded-form.keyzd2ebbfb26dd" >…...

微服务--Sentinel(实现:服务高可用)

内存溢出&#xff1a;OOM 服务器挂掉的原因&#xff1a; 1.激增流量打垮&#xff1a; 1.流量突然飙升&#xff0c;导致CPU上升&#xff0c;出现挂机 2.负载不均&#xff1a;比如一个实例长期未重启&#xff0c;导致磁盘写满降低响应时间等。 3.线程池满&#xff0c;单点故障&…...

Admin.Net中的消息通信SignalR解释

定义集线器接口 IOnlineUserHub public interface IOnlineUserHub {/// 在线用户列表Task OnlineUserList(OnlineUserList context);/// 强制下线Task ForceOffline(object context);/// 发布站内消息Task PublicNotice(SysNotice context);/// 接收消息Task ReceiveMessage(…...

CMake基础:构建流程详解

目录 1.CMake构建过程的基本流程 2.CMake构建的具体步骤 2.1.创建构建目录 2.2.使用 CMake 生成构建文件 2.3.编译和构建 2.4.清理构建文件 2.5.重新配置和构建 3.跨平台构建示例 4.工具链与交叉编译 5.CMake构建后的项目结构解析 5.1.CMake构建后的目录结构 5.2.构…...

【第二十一章 SDIO接口(SDIO)】

第二十一章 SDIO接口 目录 第二十一章 SDIO接口(SDIO) 1 SDIO 主要功能 2 SDIO 总线拓扑 3 SDIO 功能描述 3.1 SDIO 适配器 3.2 SDIOAHB 接口 4 卡功能描述 4.1 卡识别模式 4.2 卡复位 4.3 操作电压范围确认 4.4 卡识别过程 4.5 写数据块 4.6 读数据块 4.7 数据流…...

在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module

1、为什么要修改 CONNECT 报文&#xff1f; 多租户隔离&#xff1a;自动为接入设备追加租户前缀&#xff0c;后端按 ClientID 拆分队列。零代码鉴权&#xff1a;将入站用户名替换为 OAuth Access-Token&#xff0c;后端 Broker 统一校验。灰度发布&#xff1a;根据 IP/地理位写…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

IT供电系统绝缘监测及故障定位解决方案

随着新能源的快速发展&#xff0c;光伏电站、储能系统及充电设备已广泛应用于现代能源网络。在光伏领域&#xff0c;IT供电系统凭借其持续供电性好、安全性高等优势成为光伏首选&#xff0c;但在长期运行中&#xff0c;例如老化、潮湿、隐裂、机械损伤等问题会影响光伏板绝缘层…...

浅谈不同二分算法的查找情况

二分算法原理比较简单&#xff0c;但是实际的算法模板却有很多&#xff0c;这一切都源于二分查找问题中的复杂情况和二分算法的边界处理&#xff0c;以下是博主对一些二分算法查找的情况分析。 需要说明的是&#xff0c;以下二分算法都是基于有序序列为升序有序的情况&#xf…...

图表类系列各种样式PPT模版分享

图标图表系列PPT模版&#xff0c;柱状图PPT模版&#xff0c;线状图PPT模版&#xff0c;折线图PPT模版&#xff0c;饼状图PPT模版&#xff0c;雷达图PPT模版&#xff0c;树状图PPT模版 图表类系列各种样式PPT模版分享&#xff1a;图表系列PPT模板https://pan.quark.cn/s/20d40aa…...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...