The HTTP caching function is supported since version 6.0.0(20).
HTTP caching is a mechanism that stores copies of web resources on the client side. When the same resource is requested again, it can be retrieved directly from the cache without issuing a full request to the server. HTTP caching is well-suited for static resources (such as images and CSSs) and high-traffic content, effectively enhancing the performance of web resource retrieval. Remote Communication Kit module provides HTTP caching in compliance with RFC 9111. It supports independent configuration of caching policies and persistent storage paths, enabling both in-memory and disk caching, and provides support for custom cache interceptors.
The basic HTTP caching function supports phones, 2-in-1 devices, tablets, wearables, and TVs.
In scenarios requiring frequent access to online data, network request latency accounts for a significant portion of the overall duration. You can create a ResponseCache instance and configure it in the session to use the HTTP caching function, thereby improving the resource loading performance.
Import the required modules.
import { rcp } from '@kit.RemoteCommunicationKit'; Create a ResponseCache instance. In the following code, pathToFolder indicates the file path for storing HTTP response cache records. Replace /path/dir with the sandbox path for storing HTTP response cache records.
// Create a ResponseCache instance.
const responseCache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/data/storage/el2/base/entry/temp/BaseHttp' // Select an appropriate path as needed.
}
}); Creates a session and pass the responseCache instance.
const session: rcp.Session = rcp.createSession({
requestConfiguration: {
cache: responseCache,
}
}); Initiate the first request. Replace https://www.example.com with the actual URL that supports the HTTP caching protocol. This request retrieves data from the server. You can check the cache status to determine whether the retrieved data is successfully cached. If an HTTP record is cached, the cache record count changes to 1.
// The URL to request is only an example. Modify it as needed.
const responseA = await session.get('https://www.example.com');
console.info(`Request succeeded, message is ${JSON.stringify(responseA)}`);
let cacheState = await responseCache.getState();
console.info(`The current number of cache entries is: ${cacheState.count}`); Initiate the second request. The second request retrieves the response from the cache directly. At this point, you can check the cache status, and you will find that the cache hit count changes to 1.
// The URL to request is only an example. Modify it as needed.
const responseB = await session.get('https://www.example.com');
console.info(`Request succeeded, message is ${JSON.stringify(responseB)}`);
cacheState = await responseCache.getState();
console.info(`The current cache hit count is: ${cacheState.hitCount}`); Remote Communication Kit provides various cache expiration policy options for you to choose, including the permanent, absolute time-based, relative time-based, and sliding time window-based expiration policies. For details about the relevant APIs, please refer to the API Reference. You can choose a policy to flexibly adjust the cache lifecycle based on your service needs. The following uses the relative time-based expiration policy as an example to describe how to configure the cache expiration policy, so you can understand the cache logic.
Import the required modules.
import { rcp } from '@kit.RemoteCommunicationKit'; Create a ResponseCache instance. In the following code, pathToFolder indicates the file path for storing HTTP response cache records. Replace /path/dir with the sandbox path for storing HTTP response cache records. defaultExpirationPolicy indicates the default expiration policy. In the sample code, the relative time-based expiration policy with an interval of 3 seconds is configured. For details about the API, please refer to RelativeTimeExpirationPolicy.
const responseCache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/data/storage/el2/base/entry/temp/ExpirationHttp' // Select an appropriate path as needed.
},
// Set the cache expiration policy based on your service needs.
defaultExpirationPolicy: {
kind: 'relative',
time: {
units: 'seconds',
value: 3,
}
}
}); Creates a session and pass the responseCache instance.
const session: rcp.Session = rcp.createSession({
requestConfiguration: {
cache: responseCache,
}
}); Initiate the first request. Replace https://www.example.com with the actual URL that supports the HTTP caching protocol. This request retrieves data from the server. You can check the cache status to determine whether the retrieved data is successfully cached. If an HTTP record is cached, the cache record count changes to 1.
// The URL to request is only an example. Modify it as needed.
const responseA = await session.get('https://www.example.com');
console.info(`Request succeeded, message is ${JSON.stringify(responseA)}`);
let cacheState = await responseCache.getState();
console.info(`The current number of cache entries is: ${cacheState.count}`); Define the sleep function and set the delay to 4 seconds. As the cache expiration interval is set to 3 seconds, after the delay elapses, the cache record stored in step 4 will expire by then.
// Define the sleep function. The unit of the input parameter timeout is millisecond.
type sleepFn = (a: number) => Promise<null>
const sleep: sleepFn = (timeout) => {
return new Promise(resolve => {
setTimeout(() => {
resolve(null)
}, timeout);
});
};
// Set the delay to 4 seconds, for the cache record to expire.
await sleep(4000); Initiate the second request. As the cache record has already expired, this request will access the server to retrieve data. In this case, the cache hit count remains 0.
// The URL to request is only an example. Modify it as needed.
const responseB = await session.get('https://www.example.com');
console.info(`Request succeeded, message is ${JSON.stringify(responseB)}`);
cacheState = await responseCache.getState();
console.info(`The current cache hit count is: ${cacheState.hitCount}`);