Okhttp Cache Max-age and Max-stale detailed

Source: Internet
Author: User
Tags throwable

First, prefacePrior to understanding the use of okhttp cache, and the use of the cache is a preliminary summary of 80650856. The cache is primarily intended to obtain resource information directly from the cache in the absence of a network, or when resources do not need to be updated in real time to the backend. On the one hand, it can still give the user a good interface in the case of disconnection, and another aspect is to avoid the pressure on the backend by the frequent request network. At present, the implementation of the client-side caching mechanism in Okhttp is presented on the network, which is done by setting the parameter values of Max-age and Max-stale in the custom intercept. However, after consulting the methods on the network, the following questions still exist: 1. Max-age and Max-stale can be set in both the request and the response, and the effects of both settings are the same. 2. In my company's URL test found that max-age and Max-stale did not work. In order to solve these problems, it is necessary to verify and study these two parameters in actual code. the significance of the parameters of the second, max-age and Max-staleMax-age: Tells the cache how long, without exceeding the cache time, the request returns the data in the cache, initiates a new request to the server in case of exceeding max-age, and returns the cached data if the request fails ( verified in Test), or re-initiate the request to the server. Max-stale: Indicates that the client can receive a response message that exceeds Max-age time , Max-stale is valid in Request settings and is not valid in response settings(Verified in the test, see blog https://www.jianshu.com/p/db197279f053). So Max-age and Max-stale in the case of simultaneous use of the request, the cache time can be max-age and Max-stale. Third, test verificationIn the test, you need to construct a okhttp, then define different max-age and Max-stale in the interceptor to test, define a timer in activity, and make a network request every 3s. The network requests in the activity are as follows:
@Overridepublic void OnClick (view view) {if (View.getid () = = R.id.button) {observable.interval (3, Timeunit.seconds). Subscribe (new action1<long> () {@Overridepublic void call (Long along) {getrecomandcomic ();}});}} private void Getrecomandcomic () {retrofitresearch.getinstance (this). Gettoprecommendlist (). Subscribeon ( Schedulers.computation ()). Observeon (Androidschedulers.mainthread ()). Subscribe (New action1< Comicbeannocountresult> () {@Overridepublic void call (Comicbeannocountresult comicbeannocountresult) {}}, new Action1<throwable> () {@Overridepublic void call (Throwable throwable) {}});
The construction code for Okhttp is as follows:
public class Okhttpcallfactory {private static int default_timeout = 30;private static final int const_10 = 10;private STA Tic Final int const_1024 = 1024;private static final Logger Logger = Logger.getlogger ("Yansm");p rivate okhttpcallfactory () {}private static call.factory factory;private static int time =60;public static call.factory getokhttpfactory (Context con Text) {if (factory = = null) {synchronized (Okhttpcallfactory.class) {if (factory = = null) {Okhttpclient.builder Builder = New Okhttpclient.builder (); Builder.cache (new Cache (Context.getcachedir (), const_10 * const_1024 * const_1024)); Set Cache Builder.connecttimeout (Default_timeout, timeunit.seconds); Builder.writetimeout (Default_timeout, Timeunit.seconds); Builder.readtimeout (Default_timeout, timeunit.seconds); Interceptor Interceptor = new Netcacheinterceptor (); Builder.addinterceptor (Interceptor); Builder.addnetworkinterceptor (Interceptor); Builder.addinterceptor (New Logginginterceptor ()); factory = Builder.build ();}}} return factory;} //Log Output Interceptor private static class Logginginterceptor implements interceptor {@Override public Response intercept (Chain Chain ) throws IOException {Long T1 = System.nanotime (); Request Request = Chain.request (); Logger.info (String.Format ("Sending request%s on%s%n%s", Request.url (), Chain.connection (), Request.headers ())); Response Response = chain.proceed (request),  long t2 = System.nanotime (); Logger.info (String.Format ("Received Response for%s in%.1fms%n%s ", Request.url (), (T2-T1)/1e6d, Response.headers ())); return response; }}}
3.1 Set max-age = 60 and Max-stale in the response of the Interceptor =
public class Netcacheinterceptor implements interceptor {@Overridepublic Response intercept (Chain Chain) throws IOException {Request request = Chain.request (); CacheControl CacheControl = new Cachecontrol.builder (). MaxAge (Timeunit.seconds). Maxstale (Timeunit.seconds). Build (); Response Response = chain.proceed (Request), return Response.newbuilder (). Removeheader ("Pragma"). Removeheader (" Cache-control "). Header (" Cache-control ", Cachecontrol.tostring ()). build ();}}
The test log results are as follows, sending a request every three seconds:
First time Network request06-22 13:59:51.816 32336-469/com.example.moxie.cacheresearch i/yansm:sending Request http://lbs.sougu.net.cn/ App.php?m=souguapp&c=appusers&a=network on null06-22 13:59:52.200 32336-469/ Com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn/app.php?m=souguapp&c= Appusers&a=network in 381.9msserver:tenginecontent-type:text/json;charset=utf-8content-length:1492date:fri, June 2018 05:59:51 Gmtexpires:thu, Nov 1981 08:52:00 Gmtx-powered-by:php/7.0.1set-cookie:phpsessid=pef8qomvm3kjg90 BS94OJPUGF1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529647191|1529647191; PATH=/VIA:CACHE14.L2EU6-1[103,200-0,M], cache4.l2eu6-1[103,0], cache8.cn785[155,200-0,m], cache7.cn785[159,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:59:51 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:3d9bde1b15296471912141111econnection:keep-alivecache-control:max-age=60, max-stale=120 second network request 06-22 13:59:54.733 32336-469/com.example.moxie.cacheresearch i/yansm:sending Request http://lbs.sougu.net.cn/ App.php?m=souguapp&c=appusers&a=network on null06-22 13:59:54.759 32336-469/ Com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn/app.php?m=souguapp&c= Appusers&a=network in 25.1msserver:tenginecontent-type:text/json;charset=utf-8content-length:1492date:fri, 22 June 2018 05:59:51 Gmtexpires:thu, Nov 1981 08:52:00 Gmtx-powered-by:php/7.0.1set-cookie:phpsessid=pef8qomvm3kjg90bs 94OJPUGF1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529647191|1529647191; PATH=/VIA:CACHE14.L2EU6-1[103,200-0,M], cache4.l2eu6-1[103,0], cache8.cn785[155,200-0,m], cache7.cn785[159,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:59:51 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:3d9bde1b15296471912141111econnection:keep-alivecache-control:max-age=60, max-stale=120 third Network request 06-22 13:59:57.733 32336-469/com.example.moxie.cacheresearch i/yansm:sending Request http://lbs.sougu.net.cn/ App.php?m=souguapp&c=appusers&a=network on null06-22 13:59:57.749 32336-469/ Com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn/app.php?m=souguapp&c= Appusers&a=network in 14.9msserver:tenginecontent-type:text/json;charset=utf-8content-length:1492date:fri, 22 June 2018 05:59:51 Gmtexpires:thu, Nov 1981 08:52:00 Gmtx-powered-by:php/7.0.1set-cookie:phpsessid=pef8qomvm3kjg90bs 94OJPUGF1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529647191|1529647191; PATH=/VIA:CACHE14.L2EU6-1[103,200-0,M], cache4.l2eu6-1[103,0], cache8.cn785[155,200-0,m], cache7.cn785[159,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:59:51 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:3d9bde1b15296471912141111econnection:keep-alivecache-control:max-age=60, max-stale=120
Charles Capture Package Results analysis: In the experiment, the response max-age and Max-stale were set, respectively, 60 seconds and 120 seconds, which can be seen in the output of the log. But through the actual capture results can see max-age aging effect, Max-stale No aging, the client in 60s did not send a request to the server, but after 60s to the server sent a request. 3.2 Set max-age=120 and max-stale=60 in the request of the InterceptorThe reference code is as follows
@Overridepublic Response Intercept (Chain Chain) throws IOException {Request request = Chain.request (); CacheControl CacheControl = new Cachecontrol.builder (). MaxAge (Timeunit.seconds). Maxstale (Timeunit.seconds). Build (); request = Request.newbuilder (). CacheControl (CacheControl). build (); return chain.proceed (Request);
The test log results are as follows:
First time Network request06-22 13:33:28.131 29674-30389/com.example.moxie.cacheresearch i/yansm:sending Request http://lbs.sougu.net.cn/ App.php?m=souguapp&c=appusers&a=network on nullcache-control:max-age=120, max-stale=6006-22 13:33:28.700 29674-30389/com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn/app.php?m= Souguapp&c=appusers&a=network in 567.5msserver:tenginecontent-type:text/json;charset=utf-8content-length : 1492date:fri, June 2018 05:33:27 Gmtexpires:thu, Nov 1981 08:52:00 Gmtx-powered-by:php/7.0.1set-cookie:phpsessi d=t6j4tnss1nkpbm0tddqdr0o2j1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529645607|1529645607; PATH=/VIA:CACHE14.L2EU6-1[102,200-0,M], cache21.l2eu6-1[106,0], cache10.cn883[190,200-0,m], cache1.cn883[214,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:33:27 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:af06f99515296456075954226econnection:keep-alivecache-control:pubLIC, max-age=6000 Nth Network Request06-22 13:35:25.057 29674-30389/com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn /app.php?m=souguapp&c=appusers&a=network in 9.6msserver:tenginecontent-type:text/json;charset= Utf-8content-length:1492date:fri, June 2018 05:33:27 Gmtexpires:thu, Nov 1981 08:52:00 Gmtx-powered-by:php/7.0.1s et-cookie:phpsessid=t6j4tnss1nkpbm0tddqdr0o2j1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529645607|1529645607; PATH=/VIA:CACHE14.L2EU6-1[102,200-0,M], cache21.l2eu6-1[106,0], cache10.cn883[190,200-0,m], cache1.cn883[214,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:33:27 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:af06f99515296456075954226econnection:keep-alivecache-control:public, max-age=6000First n+1 network request06-22 13:35:28.046 29674-30389/com.example.moxie.cacheresearch i/yansm:sending Request http://lbs.sougu.net.cn/ App.php?m=souguapp&c=appusers&a=network on nullcache-control:max-age=120, max-stale=6006-22 13:35:28.056 29674-30389/com.example.moxie.cacheresearch i/yansm:received response for http://lbs.sougu.net.cn/app.php?m= Souguapp&c=appusers&a=network in 8.9msserver:tenginecontent-type:text/json;charset=utf-8content-length: 1492date:fri, June 2018 05:33:27 Gmtexpires:thu, Nov 1981 08:52:00 gmtx-powered-by:php/7.0.1set-cookie:phpsessid= t6j4tnss1nkpbm0tddqdr0o2j1; path=/set-cookie:serverid=37f80876073565188d4968aa47392891|1529645607|1529645607; PATH=/VIA:CACHE14.L2EU6-1[102,200-0,M], cache21.l2eu6-1[106,0], cache10.cn883[190,200-0,m], cache1.cn883[214,0] X-cache:miss Tcp_miss dirn:-2:-2 Mlen:-1x-swift-savetime:fri, June 2018 05:33:27 gmtx-swift-cachetime:0timing-allow- Origin: *eagleid:af06f99515296456075954226econnection:keep-alivecache-control:publiC, max-age=6000warning:110 httpurlconnection "Response is stale"
Charles capture the results of the test results analysis, from the test results can be seen in the request to set the Max-age and Max-stale values, the cache time is worth and, in the test max-age = 120s,max-stale = 60s, exactly 3 minutes, catch The package request interval is 3 minutes. But one thing, when requested more than 120s after the request, the result of the request will be more "warning:110 httpurlconnection" Response is stale "" 3.3 anomaly Test oneMax-age and Max-stale are expected in the above tests, but Max-age and Max-stale seem to have lost their effect when testing with the company's URL.           The test is still set max-age = 60 and Max-stale = 120 in response. The test log results are as follows:
First time Network request06-22 17:38:27.094 7756-7780/com.example.moxie.cacheresearch i/yansm:sending Request https://comic.mkzhan.com/recom /app/on null06-22 17:38:27.253 7756-7780/com.example.moxie.cacheresearch i/yansm:received response for https:// Comic.mkzhan.com/recom/app/in 158.0msserver:tenginecontent-type:application/json; Charset=utf-8content-length:625date:fri, June 2018 08:51:34 Gmtaccess-control-allow-origin: * Access-control-allow-headers:x-requested-with,app-id,app-version,device-name,device-resolution,device-udid, Platform,system-name,system-versionaccess-control-allow-methods:get,post,optionsx-powered-by:mkzhan-a2via: CACHE9.L2CM10-1[0,200-0,H], cache29.l2cm10-1[1,0], cache1.cn1412[0,200-0,h], Cache14.cn1412[1,0]age:2812x-cache: Hit Tcp_mem_hit dirn:12:43491335 Mlen:-1x-swift-savetime:fri, June 2018 09:03:10 Gmtx-swift-cachetime: 3600timing-allow-origin: *eagleid:7ce89ea215296603064393222econnection:keep-alivecache-control:max-age=60, max-stale=120 second network request 06-22 17:38:30.091 7756-7780/com.example.moxie.cacheresearch i/yansm:sending Request https://comic.mkzhan.com/recom /app/on null06-22 17:38:30.249 7756-7780/com.example.moxie.cacheresearch i/yansm:received response for https:// Comic.mkzhan.com/recom/app/in 156.9msserver:tenginecontent-type:application/json; Charset=utf-8content-length:625date:fri, June 2018 08:51:34 Gmtaccess-control-allow-origin: * Access-control-allow-headers:x-requested-with,app-id,app-version,device-name,device-resolution,device-udid, Platform,system-name,system-versionaccess-control-allow-methods:get,post,optionsx-powered-by:mkzhan-a2via: CACHE9.L2CM10-1[0,200-0,H], cache29.l2cm10-1[1,0], cache1.cn1412[0,200-0,h], Cache14.cn1412[1,0]age:2815x-cache: Hit Tcp_mem_hit dirn:12:43491335 Mlen:-1x-swift-savetime:fri, June 2018 09:03:10 Gmtx-swift-cachetime: 3600timing-allow-origin: *eagleid:7ce89ea215296603094162696econnection:keep-alivecache-control:max-age=60, max-stale=120 third Network request 06-22 17:38:33.093 7756-7780/com.example.moxie.cacheresearch i/yansm:sending Request https://comic.mkzhan.com/recom /app/on null06-22 17:38:33.198 7756-7780/com.example.moxie.cacheresearch i/yansm:received response for https:// Comic.mkzhan.com/recom/app/in 103.4msserver:tenginecontent-type:application/json; Charset=utf-8content-length:625date:fri, June 2018 08:51:34 Gmtaccess-control-allow-origin: * Access-control-allow-headers:x-requested-with,app-id,app-version,device-name,device-resolution,device-udid, Platform,system-name,system-versionaccess-control-allow-methods:get,post,optionsx-powered-by:mkzhan-a2via: CACHE9.L2CM10-1[0,200-0,H], cache29.l2cm10-1[1,0], cache1.cn1412[0,200-0,h], Cache14.cn1412[0,0]age:2818x-cache: Hit Tcp_mem_hit dirn:12:43491335 Mlen:-1x-swift-savetime:fri, June 2018 09:03:10 Gmtx-swift-cachetime: 3600timing-allow-origin: *eagleid:7ce89ea215296603123821715econnection:keep-alivecache-control:max-age=60, max-stale=120
Grab the packet The result is as follows: Set Max-age =60s in response, according to the previous test situation, the request should be 60s interval, instead of 3s per request. In response to this query, the return field in the log was checked to find that the field returned by the company server was more than the field that was previously tested the definition of an age field age field: When the proxy server responds to the request with its own cached entity, Use this header to indicate how long the entity has been from generation to present (see the blog for explanation 46460631). As can be guessed by the definition of this field, this field affects the aging of the cache, and if the defined cache is smaller than the change value, the cache may be invalidated from the setup. Therefore, you need to define the time value of Max-age to exceed the time value of age in order for the Max-age value to take effect. 3.4 Exception Test twoBecause the time value of age will also increase, set the time value of Max-age to 4000 to get the following test log:
06-22 09:52:47.578 14683-14855/com.example.moxie.cacheresearch i/yansm:sending Request https://comic.mkzhan.com/ Recom/app/on null06-22 09:52:48.216 14683-14855/com.example.moxie.cacheresearch i/yansm:received response for https:/ /comic.mkzhan.com/recom/app/in 637.9msserver:tenginecontent-type:application/json; Charset=utf-8content-length:624date:fri, June 2018 00:51:28 Gmtaccess-control-allow-origin: * Access-control-allow-headers:x-requested-with,app-id,app-version,device-name,device-resolution,device-udid, Platform,system-name,system-versionaccess-control-allow-methods:get,post,optionsx-powered-by:mkzhan-a2via: CACHE9.L2CM10-1[0,200-0,H], cache22.l2cm10-1[1,0], cache10.cn978[0,200-0,h], Cache2.cn978[1,0]age:3679x-cache:hit Tcp_mem_hit dirn:6:301393262 Mlen:-1x-swift-savetime:fri, June 2018 01:08:57 Gmtx-swift-cachetime: 3600timing-allow-origin: *eagleid:74d3999615296323674053464econnection:keep-alivecache-control:public, max-age= 4000
The result of the test is that the cache is in effect, but the time value is only 4000s-3679s = 321s, and after the age value exceeds 4000s, it is still sent every 3s clock at the interval set in the test code. In order to be able to remove the effect of age, call Removeheader in response to delete age, but it does not work. Iv. SummaryThis is mainly for the significance of Max-age and Max-stale in the use of okhttp to carry out the actual verification test, because initially with the company's URL test found inconsistent with the expected, after the discovery is the age parameter value of ghosts. Reference Blog:5136554851316116https://segmentfault.com/q/1010000002578217/a-1020000002578576https://www.cnblogs.com/_franky/ archive/2011/11/23/2260109.html52920531https://www.cnblogs.com/lenve/p/6063851.html52975183https:// www.jianshu.com/p/db197279f053 (more detailed, worth reading)

Okhttp Cache Max-age and Max-stale detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.