A general image cache solution for Mobile Application Development (IOS/android, etc.) (with a flowchart)
In mobile application development, we often encounter scenarios from network request images to display on devices.
If a request is initiated repeatedly every time, the user experience will be poor, resulting in a waste of traffic and power consumption;
Persistence of images to disks is also a policy. However, there is a certain io overhead for reading images from files each time. Even with this policy, we also need to control the disk cache capacity, to avoid occupying too many system resources.
In fact, no solution can be said to be a perfect solution. Only a solution that best suits your business needs can be said to be a good solution.
The solution described below is highly versatile and the design ideas are simple and clear:
1. Assume that the url of each network image is unique. If the image on the network changes, the url of the Input Source changes;
2. Based on 1, we use the url as the unique identifier of the image cache (which can be hash, md5, or urlstring as the key)
3. Access Priority: memory cache> disk cache> Network Resources
The above three points are the basic strategies of our solution. The following are the technical details:
1. for Cache Management, we can set the threshold value (including the cache time and cache capacity) to trigger cleaning when conditions are met. We can also combine the LRU (Least Recently Used algorithm) to improve the cache access efficiency, You need to mark the Cache Usage when writing the cache. Here, this algorithm is not expanded and you are interested in google.
2. we must adopt an asynchronous scheme for loading network resources, so that the ui display will not be blocked. We can add requests to the queue to support concurrent requests, note that you can set the maximum number of concurrent requests based on the number of URLs that can be connected simultaneously at a specific address to improve efficiency.
3. when the access to the disk cache/network resources is successful, you need to fill in the high-priority cache. When the disk cache access is successful, the memory cache is filled; when the network resource access is successful, fill in the memory cache + disk cache.
For specific use cases, we can decide whether to adopt or partially adopt this solution based on business needs, some policies in this solution can also be modified based on project requirements (for example, when the disk cache is not accessed, when the cache is cleared, and when the cache is forcibly refreshed) to meet business needs.