ImageKnife控制重要图片请求加载优先级

Signed-off-by: chongtiantian <chongtiantian1@h-partners.com>
This commit is contained in:
chongtiantian 2024-04-22 13:01:16 +08:00
parent 83075cc204
commit 2dea3a7f8a
8 changed files with 357 additions and 72 deletions

View File

@ -9,6 +9,7 @@
- 修改全局请求头覆盖request请求头
- imageKnife支持heic测试demo独立页面展示
- drawLifeCycle支持gif图
- ImageKnife控制重要图片请求加载优先级
## 2.1.2-rc.12
- 新增gif播放次数功能

View File

@ -335,13 +335,14 @@ request.skipMemoryCache(true)
### ImageKnife 启动器/门面类
| 方法名 | 入参 | 接口描述 |
| ------------------------------- | ---------------------- | ---------------------------------- |
| call(request: RequestOption) | request: RequestOption | 根据用户配置参数具体执行加载流程 |
| preload(request: RequestOption) | request: RequestOption | 根据用户配置参数具体执行预加载流程 |
| pauseRequests() | | 全局暂停请求 |
| resumeRequests() | | 全局恢复暂停 |
| isUrlExist(url, cacheType, size)| url, CacheType, Size | 判断图片是否在 缓存和磁盘中存在,如果入参是缓存,需要传入值图片大小,参数 CacheType, Size可选|
| 方法名 | 入参 | 接口描述 |
|----------------------------------| ---------------------- | ------------------------------------------------------------ |
| call(request: RequestOption) | request: RequestOption | 根据用户配置参数具体执行加载流程 |
| preload(request: RequestOption) | request: RequestOption | 根据用户配置参数具体执行预加载流程 |
| pauseRequests() | | 全局暂停请求 |
| resumeRequests() | | 全局恢复暂停 |
| isUrlExist(url, cacheType, size) | url, CacheType, Size | 判断图片是否在 缓存和磁盘中存在,如果入参是缓存,需要传入值图片大小,参数 CacheType, Size可选 |
| setMaxNumRequests(count: number) | count | 设置请求的最大并发数量 |
### 缓存策略相关
@ -446,6 +447,13 @@ export default class EntryAbility extends UIAbility {
}
```
### Queue
| 方法名 | 入参 | 接口描述 |
| ----------------------------------- | ----------------------- | ------------------------------ |
| getQueueLength(): number | | 获取队列总长度 |
| add(requestInfo: RequestInfo): void | requestInfo:RequestInfo | 在队列尾部插入元素 |
| pop(): RequestInfo &#124; undefined | | 删除队列头元素并返回该删除元素 |
## 约束与限制

View File

@ -12,71 +12,160 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ImageKnifeComponent , Priority , NONE } from '@ohos/libraryimageknife'
import { ImageKnifeComponent, ImageKnifeOption, Priority, NONE, ImageKnifeGlobal } from '@ohos/libraryimageknife';
const dataBak: ImageKnifeOption[] = [
{
loadSrc: "http://b.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81b94575cfb93eb13533fa40a2.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://e.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31c1badd5a685d6277f9e2ff81e.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://g.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c87a3add4d52a6059252da61e.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://a.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee5080c8142ff5e0fe99257e19.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://f.hiphotos.baidu.com/image/pic/item/4034970a304e251f503521f5a586c9177e3e53f9.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
priority: Priority.MEDIUM
},
{
loadSrc:"http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
priority: Priority.LOW
},
{
loadSrc: "http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
priority: Priority.LOW
},
{
loadSrc: "http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
priority: Priority.LOW
},
{
loadSrc: "http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
priority: Priority.LOW
},
{
loadSrc:"http://img2.xkhouse.com/bbs/hfhouse/data/attachment/forum/corebbs/2009-11/2009113011534566298.jpg",
priority: Priority.LOW
}
];
@Entry
@Component
struct TestPriorityComponent {
private data: string[] = [
"http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
"http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
"http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
"http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb938d5277fd5d0628535e5dd6f4a.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg",
"http://b.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81b94575cfb93eb13533fa40a2.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31c1badd5a685d6277f9e2ff81e.jpg",
"http://g.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c87a3add4d52a6059252da61e.jpg",
"http://a.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee5080c8142ff5e0fe99257e19.jpg",
"http://f.hiphotos.baidu.com/image/pic/item/4034970a304e251f503521f5a586c9177e3e53f9.jpg",
"http://b.hiphotos.baidu.com/image/pic/item/279759ee3d6d55fbb3586c0168224f4a20a4dd7e.jpg",
"http://img2.xkhouse.com/bbs/hfhouse/data/attachment/forum/corebbs/2009-11/2009113011534566298.jpg",
"http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg",
"http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
"http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
"http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
"http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
"http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg",
"http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
"http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
"https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
'https://img-blog.csdnimg.cn/20191215043500229.png',
'https://img-blog.csdn.net/20140514114029140',
'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp'
]
@State data: ImageKnifeOption[] = [
{
loadSrc: "https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
priority: Priority.HIGH
},
{
loadSrc: "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb938d5277fd5d0628535e5dd6f4a.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg",
priority: Priority.HIGH
},
{
loadSrc: "http://b.hiphotos.baidu.com/image/pic/item/279759ee3d6d55fbb3586c0168224f4a20a4dd7e.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://img2.xkhouse.com/bbs/hfhouse/data/attachment/forum/corebbs/2009-11/2009113011534566298.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
priority: Priority.MEDIUM
},
{
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
priority: Priority.LOW
},
{
loadSrc: "https://img-blog.csdnimg.cn/20191215043500229.png",
priority: Priority.LOW
},
{
loadSrc: "https://img-blog.csdn.net/20140514114029140",
priority: Priority.LOW
},
{
loadSrc: "https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp",
priority: Priority.LOW
},
{
loadSrc: "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
priority: Priority.LOW
}
];
@State maxRequests: number | undefined = ImageKnifeGlobal?.getInstance()?.getImageKnife()?.maxRequests;
build(){
Column(){
Grid(){
ForEach(this.data,(item:string,index:number)=>{
GridItem(){
if(index % 2 == 0){
build() {
Column() {
Text('最大并发数: ' + this.maxRequests).width('50%').height(30)
Button('修改最大并发数为5').width('50%').height(30)
.onClick(() => {
if (ImageKnifeGlobal?.getInstance()?.getImageKnife()) {
ImageKnifeGlobal?.getInstance()?.getImageKnife()?.setMaxNumRequests(5);
this.maxRequests = ImageKnifeGlobal?.getInstance()?.getImageKnife()?.maxRequests;
this.data = [...dataBak];
}
})
Grid() {
ForEach(this.data, (item: ImageKnifeOption, index: number) => {
GridItem() {
Flex() {
Text(item?.priority?.toString() || '')
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:item,
placeholderSrc:$r('app.media.icon_loading'),
strategy:new NONE(),
isCacheable:false,
priority:Priority.LOW
}
})
} else if (index % 3 == 0) {
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:item,
placeholderSrc:$r('app.media.icon_loading'),
strategy:new NONE(),
isCacheable:false,
priority:Priority.MEDIUM
}
})
} else {
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:item,
placeholderSrc:$r('app.media.icon_loading'),
strategy:new NONE(),
isCacheable:false,
priority:Priority.HIGH
imageKnifeOption: {
loadSrc: item.loadSrc,
placeholderSrc: $r('app.media.icon_loading'),
strategy: new NONE(),
isCacheable: false,
priority: item.priority
}
})
}
@ -85,8 +174,8 @@ struct TestPriorityComponent {
}
.width("100%")
.height("100%")
.columnsTemplate("1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr")
.rowsTemplate("1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr")
.columnsTemplate("1fr 1fr 1fr 1fr 1fr")
.rowsTemplate("1fr 1fr 1fr 1fr 1fr ")
.columnsGap(10)
.backgroundColor(0xFAEEE0)
}.width("100%").height("100%").backgroundColor(Color.Pink)

View File

@ -0,0 +1,67 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { describe, it, expect } from '@ohos/hypium';
import { ImageKnife, ImageKnifeGlobal, RequestOption } from '@ohos/imageknife/Index';
import { DefaultJobQueue } from '@ohos/imageknife/src/main/ets/components/imageknife/utils/DefaultJobQueue';
import { IJobQueue, RequestInfo } from '@ohos/imageknife/src/main/ets/components/imageknife/utils/IJobQueue';
import taskpool from '@ohos.taskpool';
import common from '@ohos.app.ability.common';
export default function DefaultJobQueueTest() {
describe('DefaultJobQueueTest', () => {
it('testJob', 0, () => {
let job: IJobQueue = new DefaultJobQueue();
job.add(makeRequest("medium1", getContext() as common.UIAbilityContext));
job.add(makeRequest("medium2", getContext() as common.UIAbilityContext, taskpool.Priority.MEDIUM));
job.add(makeRequest("medium3", getContext() as common.UIAbilityContext));
job.add(makeRequest("low1", getContext() as common.UIAbilityContext, taskpool.Priority.LOW, 'placeholder'));
job.add(makeRequest("high1", getContext() as common.UIAbilityContext, taskpool.Priority.HIGH));
job.add(makeRequest("low2", getContext() as common.UIAbilityContext, taskpool.Priority.LOW));
job.add(makeRequest("medium4", getContext() as common.UIAbilityContext));
expect(job.getQueueLength()).assertEqual(7);
expect(job.pop()!.request.loadSrc).assertEqual("high1");
expect(job.pop()!.request.loadSrc).assertEqual("medium1");
expect(job.pop()!.request.loadSrc).assertEqual("medium2");
expect(job.pop()!.request.loadSrc).assertEqual("medium3");
expect(job.pop()!.request.loadSrc).assertEqual("medium4");
expect(job.pop()!.request.loadSrc).assertEqual("low1");
expect(job.pop()!.request.loadSrc).assertEqual("low2");
expect(job.pop()).assertEqual(undefined);
expect(job.getQueueLength()).assertEqual(0);
});
it("testMaxRequests", 1, () => {
let imageKnife: ImageKnife | undefined = ImageKnifeGlobal.getInstance().getImageKnife();
if (imageKnife) {
expect(imageKnife.maxRequests).assertEqual(1);
imageKnife.setMaxNumRequests(10);
expect(imageKnife.maxRequests).assertEqual(10);
};
})
});
}
function makeRequest(src: string, context: common.UIAbilityContext, priority: taskpool.Priority = taskpool.Priority.MEDIUM, usageType: string = 'main'): RequestInfo {
let requestInfo: RequestInfo = {
request: new RequestOption(),
usageType: usageType
}
requestInfo.request.loadSrc = src;
requestInfo.request.priority = priority;
requestInfo.request.moduleContext = context;
return requestInfo;
}

View File

@ -19,6 +19,7 @@ import Transfrom from './transfrom.test'
import RequestOptionTest from './requestoption.test'
import ImageKnifeTest from './imageknife.test'
import DiskLruCacheTest from './diskLruCache.test'
import DefaultJobQueueTest from './DefaultJobQueueTest.test';
export default function testsuite() {
abilityTest()
@ -28,4 +29,5 @@ export default function testsuite() {
Transfrom()
RequestOptionTest()
ImageKnifeTest();
DefaultJobQueueTest();
}

View File

@ -42,6 +42,8 @@ import common from '@ohos.app.ability.common'
import { MemoryLruCache } from '../cache/MemoryLruCache'
import { BusinessError } from '@ohos.base'
import taskpool from '@ohos.taskpool'
import { DefaultJobQueue } from './utils/DefaultJobQueue';
import { RequestInfo } from './utils/IJobQueue';
import { GIFFrame } from './utils/gif/GIFFrame'
import emitter from '@ohos.events.emitter';
@ -87,6 +89,10 @@ export class ImageKnife {
// 开发者可配置全局缓存
engineKeyImpl: EngineKeyInterface;
private mParseImageUtil: IParseImage<PixelMap>;
// 最大并发
maxRequests: number = 1;
// 排队队列
private jobQueue: DefaultJobQueue = new DefaultJobQueue();
private constructor() {
this.mParseImageUtil = new ParseImageUtil();
@ -717,6 +723,15 @@ export class ImageKnife {
request.loadComplete(mainCache);
return;
}
// 判断是否要排队
if (this.runningMaps.size() > this.maxRequests) {
this.jobQueue.add({ request, usageType });
return;
}
this.executeTaskQueue(request, usageType);
}
private executeTaskQueue(request: RequestOption, usageType: string) {
//组装可以通过sendable传递的数据
let sendData:SendableData = this.assembleSendableData(request, usageType);
//其他不能sendable发送的数据
@ -770,12 +785,27 @@ export class ImageKnife {
request.loadError("request resources error")
}
}
this.dispatchNextJob();
}).catch((err: BusinessError | string) => {
request.loadError(err)
request.loadError(err);
this.dispatchNextJob();
})
}
// 分发下一个任务
dispatchNextJob() {
let requestInfo: RequestInfo | undefined = this.jobQueue.pop();
if (requestInfo?.request && requestInfo?.usageType) {
this.executeTaskQueue(requestInfo.request, requestInfo.usageType);
}
}
// 设置请求的最大并发数量
setMaxNumRequests(count: number) {
if (count > 0) {
this.maxRequests = count;
}
}
private keyNotEmpty(request: RequestOption): boolean {
if (
request.generateCacheKey != null && request.generateCacheKey.length > 0 &&
@ -906,8 +936,8 @@ async function taskExecute(sendData:SendableData,taskData:TaskParams): Promise<P
newRequestOption.thumbDelayTime = sendData.getThumbDelayTime();
newRequestOption.size = taskData.size;
if(taskData.loadSrc){
newRequestOption.placeholderSrc = taskData.loadSrc as PixelMap | Resource | undefined;
if(taskData.placeholderSrc){
newRequestOption.placeholderSrc = taskData.placeholderSrc as PixelMap | Resource | undefined;
}
if(taskData.errorholderSrc){
newRequestOption.errorholderSrc = taskData.errorholderSrc as PixelMap | Resource | undefined;

View File

@ -0,0 +1,47 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { IJobQueue, RequestInfo } from './IJobQueue';
import Queue from '@ohos.util.Queue';
import taskpool from '@ohos.taskpool';
export class DefaultJobQueue implements IJobQueue {
highQueue: Queue<RequestInfo> = new Queue();
normalQueue: Queue<RequestInfo> = new Queue();
lowQueue: Queue<RequestInfo> = new Queue();
getQueueLength(): number {
return this.highQueue.length + this.normalQueue.length + this.lowQueue.length;
}
add(requestInfo: RequestInfo): void {
if (requestInfo.request.priority === undefined || requestInfo.request.priority === taskpool.Priority.MEDIUM) {
this.normalQueue.add(requestInfo);
} else if (requestInfo.request.priority === taskpool.Priority.HIGH) {
this.highQueue.add(requestInfo);
} else {
this.lowQueue.add(requestInfo);
}
}
pop(): RequestInfo | undefined {
if (this.highQueue.length > 0) {
return this.highQueue.pop();
} else if (this.normalQueue.length > 0) {
return this.normalQueue.pop();
} else {
return this.lowQueue.pop();
}
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { RequestOption } from '../../imageknife/RequestOption';
export interface IJobQueue {
/**
* 获取队列长度
* @returns
*/
getQueueLength(): number;
/**
* 往队列中添加元素
* @param RequestObject
*/
add(requestInfo: RequestInfo): void;
/**
* 移除并返回队列头部的元素
* @returns
*/
pop(): RequestInfo | undefined;
}
export interface RequestInfo {
request: RequestOption;
usageType: string;
}