Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
0
Yes and no. The actual schema cache can be found under ActiveRecord::Base.connection.schema_cache, but the act of calling connection causes it to be opened. If ActiveRecord::Base.connected? if false you can assume there is no schema cache, and if it is true you would have to inspect the @columns ivar of your schema_cache instance.
This is hacky because the Active Record pattern assumes that objects are connected to a datasource. If you need domain objects that are independent of your DB, I would recommend writing them as POROs using Virtus + ActiveModel::Validation, or dry-struct etc.
Share
Improve this answer
Follow
answered May 25, 2017 at 0:28
Adam LassekAdam Lassek
35.3k1414 gold badges9292 silver badges108108 bronze badges
Add a comment
|
|
Suppose I have a ActiveRecord class "User".
I realize the first time I use it via User.new, Rails makes a call to the database to get the actual attributes of User from the users table. Subsequent times it is cached, and doesn't require a database call.
This is fine.. and straightforward in a single thread.
Suppose I have multiple threads running in a single process. The first thread that calls User.new (or anything that involves User, such as finding one), will lookup the attributes in the database. The subsequent ones will have them cached.
Is there a way to check to see if the ActiveRecord attributes are cached or not?
I don't want to have to always check out a database connection via ActiveRecord::Base.connection_pool.with_connection when I call User.new, when I don't plan on using the database connection - Yes not even saving it.
u = nil
ActiveRecord::Base.connection_pool.with_connection do # I don't want to checkout a conn if User attributes are cached.
u = User.new
end
#manipulation of u. but u.save NEVER ever gets called.
I won't fully explained my entire reasoning, but doing so would detract people from answering because in a word: it's complicated. Here's an article if interested though that is similar to my problem: https://bibwild.wordpress.com/2014/07/17/activerecord-concurrency-in-rails4-avoid-leaked-connections/ I basically do NOT want to checkout a database connection if possible, but still want to call User.new to manipulate with it but NOT save it.
|
How do I know Rails has loaded/cached an Activerecord class attributes?
|
0
If possible would be good to have different query parameter for that specific case.
I think it's not possible to achieve something like that, it's seems that patterns for glob properties in /ignoreUrlParams don't work.
https://experienceleague.adobe.com/docs/experience-manager-dispatcher/using/configuring/dispatcher-configuration.html?lang=en#designing-patterns-for-glob-properties
Share
Improve this answer
Follow
answered May 8, 2021 at 16:27
mkovacekmkovacek
31022 silver badges1717 bronze badges
Add a comment
|
|
I have a requirement to cache
/etc/clientcontext/default/content/jcr:content/stores.init.js?path=xxxxx
But I am using url parameter "path" for some other urls also so cannot use /ignoreUrlParams.
Is there any way to use /ignoreUrlParams for specific url?or Is there any different way to solve this problem?
|
Can we configure /ignoreUrlParams for a specific url?
|
0
Do you have caching software on your web server? If yes is it enabled? Since some can be disabled such as UnixyVarnish what is mainly found in cPanel. Images do get cached by default. Regardless of how its displayed. And your browser should automatically cache websites you visit, unless you have disabled it.
Share
Improve this answer
Follow
answered Sep 1, 2016 at 17:20
OSKaliOSKali
3855 bronze badges
Add a comment
|
|
While tuning my web app, I noticed that certain of my images are never loading from cache, even though they're completely static:
This particular file always loads from the server, but it should be cached. The only thing somewhat special about the file, AFAICT, is that it's sourced via a CSS class, which specifies the file via a background-image style. I'm not specifying any tricky headers or anything; it's just a regular jpg file.
There's a lot online about preventing caching, but I can't find anything about making it work when it doesn't seem to be.
|
Do css background images not get cached by default?
|
0
If the JSON response has a key that identifies each object, the best practice is updating objects using the primary key.
To define primary key your models, override primaryKey() class method.
See,
https://realm.io/docs/swift/latest/#primary-keys
Then when you caching the responses, you can use add(update:) with update parameter true . That allows you to just the responses adding to the Realm regardless whether existing or not. You can download the responses every time, then just store it. Realm looks up existing value by the key and updates it. You do not need to care the value exist or not.
Share
Improve this answer
Follow
answered Jul 11, 2016 at 4:03
kishikawa katsumikishikawa katsumi
10.5k11 gold badge4242 silver badges5454 bronze badges
Add a comment
|
|
I'm using realm to cache the JSON response from the server on iOS devices, and when i open the app again, i should show the cached data until the server gives me a new JSON response to load.
I know it should be make the request with the timestamp from last request, to check if there is a new response or not, but this is not implemented yet, The server send me JSON object every time, event if it's not changed.
Now, i'm asking for the best practice to handle the cached response and the response from the server on the client side.
|
Caching and loading Data from server on iOS
|
Since the ansible git module should force the checkout (when using force=yes), stale files could be the result of a running process keeping an handle on files which should have been updated.
Check if that is the case, or if you see any error message.
From the Travis job (which fails), I can see:
TASK [app_server : Checkout eclaim source code] ********************************
task path: /root/django_deployment/django_app_server_db_server/deployment/roles/app_server/tasks/main.yml:122
skipping: [localhost] => {"changed": false, "skip_reason": "Conditional check failed", "skipped": true}
It might be fixed in issue 14438 (and Ansible 2.1)
But in this case, this is simpler: the Low Kian Seong confirms in the comments:
I am over-writing one of my own files!
So the checkout works fine, but some files get re-written.
|
I am using an ansible-playbook for my deployment and am using git to checkout my source code. The problem I am having is, I keep on getting stale versions of my source. I don't know why this is happening. It was okay before this. Is there a way to disable the cache is there is one ?
- name: Checkout eclaim_revamp source code
git: repo={{ deployment_url }} dest=/opt/eclaim_revamp force=yes version={{ eclaim_branch }} key_file=~/.ssh/id_travis accept_hostkey=yes
when: app_version == "eclaim_revamp"
Above is the declaration that I use to checkout my source code from bitbucket. Any help would be appreciated.
More information
I am running this playbook against a docker image I created.
|
Is there a cache in ansible git module?
|
0
volley (and i guess all other caching systems) use the exact detailed url u call as a key for cache data.
if you wanna delete a cache entry u need to do it by exact full link.
the link "www.example.com/amir?id=1" is different from "www.example.com/amir?id=2". otherwise caching would be more trouble than efficient.
Share
Improve this answer
Follow
answered Aug 30, 2016 at 6:40
Amir ZiaratiAmir Ziarati
14.6k1111 gold badges4949 silver badges5252 bronze badges
Add a comment
|
|
Actually I have a small confusion regarding volley cache management. Suppose I have an API with BASE URL http://example.com but when I am calling my api I am appending one layout params so finally it looks like http://example.com?sort_by=distance.
So if I want to clear the cache for this url which one should my key
http://example.com or http://example.com?sort_by=distance
And if answer is second one then do I need to clear cache independently for all the url that created by different url params.
|
Which url needs to be invalidate for clearing volley cache?
|
0
I noticed the same thing, it's frustrating. But you can click the 'Disable Cache' option in the Chrome Network inspector and it will/should remove it (In my case I just needed it to update the cache with a new Auth header).
This is concerning though because if a user logs into an app and the token expires, the app could refresh it and serve the new token to the http client, but Chrome will automatically overwrite it with the expired token...
Share
Improve this answer
Follow
answered Jun 9, 2017 at 18:24
Chris GregoryChris Gregory
8555 bronze badges
1
The OP already mentioned using this feature, but claims to still receive the error.
– Josiah Yoder
Apr 28, 2021 at 12:31
Add a comment
|
|
I am reading about HTTP basic authentication. On the MDN website, it says:
Because BA header has to be sent with each HTTP request, the web browser needs to cache the credentials for a reasonable period to avoid constant prompting user for the username and password. Caching policy differs between browsers. Microsoft Internet Explorer by default caches them for 15 minutes.
However, after I told the chrome postman to send a request without a cached header I still noticed the presence of an authorization field when I logged traffic at the server side:
{ host: 'localhost:3000',
connection: 'keep-alive',
authorization: 'Basic YWRtaW46cGFzc3dvcmQ=', // why?
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
'cache-control': 'no-cache',
'postman-token': '7e458c2d-b11b-026d-809b-68a7cf3d5a37',
....
Then I also tried using just google chrome, but I again saw an authorization field:
{ host: 'localhost:3000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
authorization: 'Basic YWRtaW46cGFzc3dvcmQ=', // again
....
Question 1: I disabled cache for both Chrome (I couldn't find the no-cached option, so I just selected "disable cache" in the chrome debugger) and postman (which has an option for "no-cached header"), but they still included the authentication header...why? How can I prevent them from doing this?
Question 2: Same thing happened when I tried to make the client not to send back the Cookie, I even use the clear cookie functionality in chrome history... but I still see its presence in request header. I assume each header field is cached differently, so how can I manage the cookies?
Opening an incognito window will make the browser forget about the authorization and cookie... but only once: subsequent tabs will have these headers.
|
How can I disable cache for http headers?
|
0
For problems like that I normally implement my custom history stack and map the back button to it.
document.addEventListener('backbutton', backHistory, false);
EDIT:
I want to say, is that I implement my own history mechanism, every link in the app that is clicked is added to a history array, like this:
history.push(url);
So, when I want to go back:
backHistory = function() {
var url = history.pop();
//Js function to navigate
}
Share
Improve this answer
Follow
edited May 26, 2016 at 17:23
answered May 25, 2016 at 21:38
BreixoBreixo
2,95022 gold badges1515 silver badges99 bronze badges
1
This still accesses the cached copy of the page so I am unable to reload everything as no javascript will execute.
– jsbuechler
May 26, 2016 at 13:30
Add a comment
|
|
So I'm currently trying to figure out a way to fully reload a page of an Android Cordova webview app when that page is navigated to via the Android back button.
Currently, when the back button is clicked, the app will open a cached version of the page with all user input still in the input fields. We need the fields to be empty when the user hits the back button.
I've done a lot of searching today and the most promising/relevant suggestion I've come across is to use 'onpageshow' and check to see if the page transition is persisted or not and then either reload the page or not.
The problem I'm having is that 'onpageshow' seems to behave in the exact same manner as 'onpageload' and will not trigger when a page loads via the back button.
Unfortunately I can't post any code as this is for my work so if you can't help me then that's fine but I'm just hoping someone has a suggestion.
|
'onpageshow' not triggering on Android WebView app
|
After some testing, I found that the problem was that I was not using ssl. if I enable ssl (https) the cache usually happens.
Then during the development of the site I'm using http, when I need to experiment with cache I use https.
I do not know why this happens but at least figured out how to solve this problem and continue development.
Thank you truly for all the help :)
|
I have font files within my JSF 2.2 project with Primefaces 5.3 and Omnifaces 2.3 and need to put these text font files (as .woff and .woff2) within the wildfly cache but unfortunately I'm not getting.
Image files (.gif, .png) and CSS files are in the cache, only text fonts that are not in the cache.
I used the tips from this site, but still could not make it work: https://gist.github.com/remibantos/5e86829e1ba6ad64eea1
I put these predicate within the wildlfy: ... path-suffix [ '.woff2'] or path-suffix [ '.woff2.xhtml'], and yet I can not have the cache.
Follows the code WildFly 10 to use to perform the cache:
standalone-full.xml
<subsystem xmlns="urn:jboss:domain:undertow:3.0">
<server name="default-server">
<host name="default-host" alias="localhost">
<filter-ref name="custom-max-age" predicate="path-suffix['.js'] or path-suffix ['.js.xhtml'] or path-suffix ['.json'] or path-suffix ['.json.xhtml'] or path-suffix ['.html'] or path-suffix ['.css'] or path-suffix ['.css.xhtml'] or path-suffix ['.jpg'] or path-suffix ['.jpg.xhtml'] or path-suffix ['.jpeg'] or path-suffix ['.jpeg.xhtml'] or path-suffix ['.png'] or path-suffix ['.png.xhtml'] or path-suffix ['.gif'] or path-suffix ['.gif.xhtml'] or path-suffix ['.eot'] or path-suffix ['.eot.xhtml'] or path-suffix ['.ttf'] or path-suffix ['.ttf.xhtml'] or path-suffix ['.woff'] or path-suffix ['.woff.xhtml'] or path-suffix ['.woff2'] or path-suffix ['.woff2.xhtml']"/>
</host>
</server>
<filters>
<response-header name="custom-max-age" header-name="Cache-Control" header-value="max-age=64800000, public"/>
</filters>
</subsystem>
Please, help me with this problem.
Thx.
|
How to Cache fonts (.woff, woff2, .ttf, .eot) in Wildfly 10?
|
0
Have you tried to hook up another event handler within the webRequest API in order to manipulate the http headers before Chrome takes on authentication?
E.g. onBeforeSendHeaders or onHeadersReceived
Share
Improve this answer
Follow
answered Jun 9, 2016 at 19:36
Carl in 't VeldCarl in 't Veld
1,42333 gold badges1515 silver badges2929 bronze badges
1
2
Unfortunately Chrome does not allow modifying "Proxy-" headers when using onBeforeSendHeaders or onHeadersReceived.
– tripRev
Nov 25, 2018 at 23:19
Add a comment
|
|
I am building a "proxy client" extension for chrome and i have following scenario:
Users can login to the extension and get a token from API. Tokens are valid for 2 hours.
After login users can select a proxy server from a list and that proxy is set with chrome.proxy api.
I am using Squid on proxy servers. When a user connects to a proxy server and lands on onAuthRequired i return email and token as authCredentials.
Chrome uses those credentials from cache until token is not valid anymore and proxy server responses "407, Proxy Authentication Required". Now the problem i am facing here is when i login with another username on same browser and connect to same proxy server it still sends old users credentials to the server because they are still valid. My question is how can delete chromes proxy auth cache so that it lands onAuthRequired again and i can return new users Credentials.
I tried to modify the response from proxy server to "407, Proxy Authentication Required" when user makes his first request over the proxy server to force a onAuthRequired but its not working. Chrome still uses cache and still returns credentials from old user to the proxy server.
|
How to delete Proxy-Authorization Cache on Chrome extension?
|
0
It is clear that, in stable condition with the read cache full, it needs more than 70% of disk cache.
Not all queues in read cache contain loaded data. The a1out queue which consumes 50% of disk cache size contains only information about pages which were loaded in a1in queue. So this queue contains so called "ghost entries" which in reality do not affect disk cache memory consumption. This queue is needed to provide additional statistical data overcome disadvantages of simple LRU cache.
Some space is took from the write cache or simply more space from the start is given to the read cache
Write cache and read cache share the same memory space, but part of the space exclusively belongs to write cache.
the "disk cache" involved is the RAM included with a common disk (HDD or SDD) and not the RAM of the machine;
We use RAM of server and do not use HDD buffer.
The default space of disk cache used by orientdb is 100%
It is used on 100% in case of high load of data, otherwise 15% now (not 30% as it is stated in documentation) is used only for write cache so is not used without presence of high data load.
Share
Improve this answer
Follow
answered Apr 18, 2016 at 15:20
Andrey LomakinAndrey Lomakin
65533 silver badges1212 bronze badges
Add a comment
|
|
I found out from the Docs that, given 100% usage of disk cache by orientdb, it uses a maximum size of 70% for read cache and 30% for write cache (http://orientdb.com/docs/last/plocal-storage-disk-cache.html#interaction-between-read-and-write-caches).
Reading more about the read cache, it's divided by 3 queque: a1in, a1out and am which their respectively maximum sizes are 25%, 50% and 75% of the read cache size (http://orientdb.com/docs/last/plocal-storage-disk-cache.html#queue-sizes).
It is clear that, in stable condition with the read cache full, it needs more than 70% of disk cache for the read cache. How is this handled? Some space is took from the write cache or simply more space from the start is given to the read cache?
Also, I would like to be sure that:
the "disk cache" involved is the RAM included with a common disk (HDD or SDD) and not the RAM of the machine;
the default space of disk cache used by orientdb is 100%, as written in the first link (possible to change with storage.diskCache.bufferSize parameter)
Thanks everyone!
|
How disk cache in OrientDB is separated by read and write cache (percentages)
|
0
Try spark.storage.memoryFraction instead.
Share
Improve this answer
Follow
answered Mar 15, 2016 at 18:20
Dmitry DzhusDmitry Dzhus
60133 silver badges88 bronze badges
1
Unfortunately, that does not affect the properies at all, either =/
– luring
Apr 13, 2016 at 12:06
Add a comment
|
|
I am trying to change the spark environment variable "spark.memory.storageFraction". I have tried to do this in various ways:
As a parameter to my spark-submit command
Saved in a config file that I attached to my spark-submit
In the scala code via .set("spark.memory.storageFraction","0.1")
When i check the spark application UI under "Spark properties" it clearly shows that the variable is set, but it has no effect on the storage memory when I look at the "Executors"-section of the UI.
Even if I add a nonsense value like such:
.set("spark.memory.storageFraction","Blah blah blah")
The program doesn't seem to be affected at all. In fact, the "blah blah blah"-value is displayed under spark properties.
I am using spark 1.5
|
Setting spark storageFraction has no efffect. It doesn't even crash with nonsense value
|
0
If "Sliding Expiration" means "Key Eviction" then you have an answer here.
Share
Improve this answer
Follow
edited May 23, 2017 at 12:08
CommunityBot
111 silver badge
answered Feb 21, 2016 at 20:19
Cosmin IonițăCosmin Ioniță
3,86055 gold badges2727 silver badges5151 bronze badges
1
6
The linked answer is not what OP is asking about. Sliding Expiration means when a key gets a hit its expiration countdown is reset by the absolute expiration time specified when the key was created in the cache. Hence why it's called "sliding" expiration. What you've linked is what Redis does when it is out of memory and how it makes more room to accept new keys, i.e., if you want it to make more room. You could have it reject the writes by using the "noeviction" policy on maxmemory, which is the default behavior.
– praneetloke
Jul 21, 2016 at 21:56
Add a comment
|
|
Does Redis support sliding expiration natively? If not, what is the best workaround?
Thanks,
Pavan.
|
Redis Cache - Native support for Sliding Expiration
|
0
It seems today that accessing the picture through the graph is a pointer to the "current" resource. So, the url in your style rule is a method to retrieve the current picture. The graph url is a no-cache url because it redirects to the current resource (i.e. it isn).
So, for the browser to cache it seems to be difficult without forcing an assumption that the image has not changed.
Depending on your situation, proxying the request through your app server would give you some cache control. You could forego the cache header manipulation and use the proxy in conjunction with Angular's $cacheFactory to keep those objects in memory during the state of the app or until you remove them from the Cache you create. Definitely use caution with caching into memory with the amount of data you can potentially have.
Share
Improve this answer
Follow
answered Jan 18, 2016 at 19:34
Stephen J BarkerStephen J Barker
1,00999 silver badges1616 bronze badges
2
I kinda get what you mean, but if you look at the comments on the OP you'll see that it appears like the images are being cached, any response to that?
– JVG
Jan 18, 2016 at 19:57
It seems the images are being cached but the browser doesn't recognize that the image belongs to the redirect url in the inline styles. So the cached image belongs to the fbcdn.net url and not the facebook.com url. Browsers get freedom to handle this how they want so many times you have to bank on the original URL's policy, which in this case is telling the browser to revalidate.
– Stephen J Barker
Jan 18, 2016 at 20:43
Add a comment
|
|
There is a similar question here, but this does not appear to apply for my circumstances.
I'm building an app using Angular-Material. I have tabular data of about 5,000 rows, and I'm loading them in to a virtual-repeat container.
If you're unfamiliar, in short this limits the displayed data to as many rows fit in the viewport, and dynamically loads in/out data as the user scrolls, dramatically decreasing the page load. It's fantastic! (I've gone from a ~30s load time to >1s)
However, I have a cell in each row that pulls in an image from Facebook, looking like:
<div style="background-image:url(https://graph.facebook.com/120945717945722/picture?width=200&height=200&)" class="avatar"></div>
When I scroll down the page these images load fine, but as they're removed from the DOM it seems that they're not cached; when I scroll up and down the repeated table, the images load from scratch again and again.
How can I ensure that they're downloaded once and then cached properly?
To clarify, each repeated item has a different image, but the image for each item doesn't change (they all come from the facebook avatar associated with a particular organisation).
|
Caching images in AngularJS (using md-virtual-repeat)
|
0
I believe the ExoPlayer does not support caching or saving the video. At least thats what this issue in Sept 2015 says.
You might be able to grab the output buffer and write that as a file.
Safest method probably is to persist the video on your own in the background (means double bandwidth usage) and then do a check whether it was downloaded yet before starting streaming.
Share
Improve this answer
Follow
answered Feb 22, 2018 at 8:40
Oliver MetzOliver Metz
3,26022 gold badges2424 silver badges3535 bronze badges
Add a comment
|
|
YouTube uses ExoPlayer in Android to play their Videos/Audios but you may have noticed , once you played a video , the next time it plays from the Cache, not from the server stream. I need to add this functionality on my Player, where should I do the customization to get that? OR anyone else (Except YouTube) did that? Proper link or suggestion would be helpful. Thanks
|
Cache Implementation for ExoPlayer in Android
|
0
I believe to resolve this you need to set the serializer for redis, the default serializer is probably not aware of the the PHP classes and when the object is removed from cache, and unserialized, it is not the same type as it was prior to serialization.
$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
For you case you will probably need to set the configuration option as a part of the driver configuration.
Share
Improve this answer
Follow
answered Jun 9, 2017 at 15:33
XildatinXildatin
14611 silver badge44 bronze badges
Add a comment
|
|
I'm trying to use Redis as a driver for caching doctrine metadata, query and results. Follwing is my configuration.
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
result_cache_driver:
type: redis
host: %redis_host%
instance_class: Redis
query_cache_driver: redis
#metadata_cache_driver: redis
When I remove the comment from line #metadata_cache_driver: redis, I get an error running a test I have with following error.
TypeError: Argument 1 passed to Doctrine\ORM\Mapping\ClassMetadataFactory::wakeupReflection() must implement interface Doctrine\Common\Persistence\Mapping\ClassMetadata, string given, called in vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php on line 214
My Functional Test looks like Following:
public function testX()
{
//The data in prepared in setup..
$param1 = 'test-id';
$param2 = 'test-key';
$result = $this->em->getRepository('MyBundle:Test')
->findOneByXX($param1, $param2);
$this->assertTrue($result instanceof Test);
}
And My Query looks like following:
$qb->select('c')
->from('MyBundle:Test', 'c')
->where('c.id = :id')
->andWhere('c.key = :key')
->setParameter('id', $id)
->setParameter('key', $key);
$query = $qb->getQuery()
->useResultCache(true);
return $query->getOneOrNullResult();
Do I need additional configuration for Redis? Any Help would be appreciated??
|
Symfony2 Doctrine Metadata Cache with Redis Issue
|
0
(should be a comment) Set the PYTHONDONTWRITEBYTECODE environment variable, which should do the same thing.
Share
Improve this answer
Follow
answered Dec 14, 2015 at 19:38
JohnJohn
47344 silver badges1313 bronze badges
Add a comment
|
|
When using Python from the command line, one can suppress the output of the _pycache_ directory using the command line option -B. Unfortunately, I wasn; able to find how to suppress this output in iPython.
What I have to do when I change a cached module with iPython is the following:
Exit from the interpreter
Remove the _pycache_ folder manually
Enter the interpreter again
As you can imagine, this procedure is really annoying!
Is there any way to suppress the _pycache_ folder with iPython?
|
Avoid _pycache_ with iPython
|
0
I think the approach of using the HTML5 local storage is the best and the only possible in caching data larger then 100kb on the client side, but it would be hard for you to deserialize, unless you store you object as json string to the local storage, Since local storage or HTML5 is an issue you can always use cookie, but, if it really 3mb (cant imagine the size of that drop-down) it will not be possible since cookie can store MAX~5KB
Share
Improve this answer
Follow
edited Dec 11, 2015 at 5:24
answered Dec 11, 2015 at 5:22
COLD TOLDCOLD TOLD
13.5k33 gold badges3535 silver badges5252 bronze badges
2
Cookie limit is 4KB. Cookies do not fit here because they are meant to store information like user preferences, configuration settings etc and not the actual data itself.
– Nikhil Vartak
Dec 11, 2015 at 5:24
Cookies are there to store text, cookie has no idea what you store in it user preferences, configuration settings are still text, maybe it will not be used as it typically used but it does not mean that you cant store text other than what you mentioned.
– COLD TOLD
Dec 11, 2015 at 5:27
Add a comment
|
|
SCENARIO: I have a GridView which has DropDownList in each row that gets bound on rowbound event. This data comes from Database and doesn't change very often. (say it changes weekly). As per my understanding the database it hit as many times as there are rows in GridView. One thing that I can do to minimize database hits is to use ViewState or session. BUT, the dropdown data will still be transferred to client side again and again. This is huge data (3MB).
Even I use ajax calls there would still be a lot of data being transferred.
It might not be an issue for fast internet connections but for slow internet connection will result in slowdowns. I was wondering if I can save dropdown data on client side and and bind it from there?
I came across an article that explains how I can store data on clientside in HTML5 CLIENT SIDE CACHING
But I would like a solution that works on browsers that dont support HTML5 as well. What would by my best bet and why?
|
ClientSide caching DropDownList with HUGE amount of data?
|
0
One solution would be to look at the file metadata for it's last modified date and compare that to a set expiration period.
For example:
import os
expiration_seconds = 3600
last_modified_time = os.path.getmtime(file_path) # i.e. 1223995325.0
# that returns a float with the time of last modification since epoch,
# so there's some logic to do to determine time passed since then.
if time_since_last_modified >= expiration_seconds:
# delete the file
os.remove(file_path)
# then do your logic to get the file again
Share
Improve this answer
Follow
answered Aug 28, 2019 at 20:26
Gabrielle Simard-MooreGabrielle Simard-Moore
53966 silver badges66 bronze badges
Add a comment
|
|
So i have read the Django-Docs about caching and understood i can cache data per view which is what i want to do. I have a URL like this : www.mysite.com/related_images/{image_id}.
which calculates related images for the selected {image_id} and saves them to the disk so they can be accessed by the template. Thing is i don't want those images to stay there forever, but right now my view saves them to the disk without any caching, how can i make sure that by caching the view for a certain period of time, any files created by the view will be deleted when the cache expires ?.
Or if you have a better solution for my problem, I'm open for ideas. Is there a way to inject images from cache into templates without saving them on disk and providing a path for the html explicitly ?
here's a simplified version of the view:
def related_image(request, pk):
original = get_object_or_404(Image, pk=pk)
images = original.get_previous_views()
for im in images:
path = '/some/dir/'+str(im.id)+'.jpg'
calculated_image = calculate(im,original)
file = open(path)
file.write(calculated_image)
im.file_path = path
return render_to_response('app/related_image.html', {'images': images})
Thanks :)
|
Python-Django Caching images
|
0
Maybe you should add permissions to cache directory
chmod 777 -R cache
Share
Improve this answer
Follow
answered Oct 28, 2015 at 11:43
Thomas ShelbyThomas Shelby
1,35033 gold badges2020 silver badges3939 bronze badges
1
I did it now but I have allways the same error : EntityManager_56274d8036816.php ...failed to open stream: No such file or directory
– Sami
Oct 28, 2015 at 15:01
Add a comment
|
|
After a cache:clear I have this in php log :
PHP Warning: require_once(/var/www/mysite/releases/20150706130613/app/cache/prod/jms_diextra/doctrine/EntityManager_56274d8036816.php): failed to open stream: No such file or directory in /var/www/mysite/releases/20150706130613/app/cache/prod/appProdProjectContainer.php on line 279
I check the file list in app/cache/prod/jms_diextra/doctrine/, I find EntityManager_XXXX.php where XXXX.php is allways different from 56274d8036816 !! So i duplicate the existing file with the required file name and then it works !! The strange thing is it' allways the same file name (56274d8036816) symfony need and never find/generate !!
I don't want to manually create the needed file each time I clear the cache :( what's going wrong ??
|
Symfony2 : clear cache don't generate required file EntityManager_XXXX.php (for doctrine)
|
0
We ran into caching problems with http://dukecon.org. Please check out the discussion here: how to selectively disable cache for spring boot (manifest.appcache).
Maybe the second part of our solution will address your issue too: Setting a no-cache header for the index.html file? This is performed with a ServletFilter: https://github.com/dukecon/dukecon_server/blob/master/impl/src/main/java/org/dukecon/server/impl/CacheManifestFilter.groovy
HTH!
Share
Improve this answer
Follow
answered Oct 19, 2015 at 17:06
Gerd AschemannGerd Aschemann
49455 silver badges1414 bronze badges
Add a comment
|
|
We are using HTML5 application cache in our single-page-web-application. The manifest-file is defined in the -tag of the index.htm-file:
<html xxxxxxxxxxxxxxxxxxxxxxxxxxxxx manifest="/xxxxxx/xxxxx.appcache">
The index.htm-file is the only htm-file which is loaded from the webserver because the web-application is single-page-web-application build with angularJS. All the following responses are in JSON.
Now we would like that the index.htm-file is not cached in the HTML5 application cache. But because the manifest-file is defined in the index.htm-file this later file is also implicitly cached.
Does anyone know how this could be done that the index.htm-file is not cached although the manifest is defined in the index.htm-file?
|
HTML5 application cache: How to exclude the htm-file from cache where the manifest is defined
|
0
This tag should do the trick.
<meta http-equiv="expires" content="0">
This meta tag will set the content expiry as 0, which means browser will hit the server every time a page is requested.
Share
Improve this answer
Follow
answered Sep 4, 2015 at 7:54
aksappyaksappy
3,43533 gold badges2525 silver badges5050 bronze badges
2
Is it possible to hit server only when files are changed
– Monicka Akilan
Sep 4, 2015 at 7:56
Depending upon the server that you are using, I would say. Which server are you using?
– aksappy
Sep 4, 2015 at 9:01
Add a comment
|
|
How to avoid website loading from cache if i have done changes in html or css file.
While browsing i gone through this question
How to avoid browser caching issues by renaming css file
But it give solution only for css not for html changes...
Please help me to figure out this issue..
Thanks in advance..
|
Avoid browser cache loading if website updated
|
0
AFHTTPSessionManager uses cookies to cache requests.
Simply delete cookies.
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
Share
Improve this answer
Follow
answered Aug 14, 2017 at 8:33
Mantas LaurinavičiusMantas Laurinavičius
9411212 silver badges2323 bronze badges
Add a comment
|
|
I have a standard subclass of AFHTTPSessionManager. I am using the initWithBaseURL:sessionConfiguration: initializer by providing the session configuration I need. I am setting the requestCachePolicy variable on the configuration with the intention that all requests will follow the given cache policy. However, if I am to check the policy of the request on any of the NSURLSessionDataDelegate callback methods, it is not set to the value on the configuration. To solve this I need to set the cachePolicy variable of the requestSerializer of the session manager.
Seems that when AFNetworking is making NSURLRequest objects it is not using the cache policy value set in the session configuration object. That said, what is the reason for setting the cachePolicy on the session configuration as opposed to the requestSerializer ?
Is this a bug or an incomplete feature in AFNetworking 2.0 or I am missing something here ?
|
iOS: AFNetworking's AFHTTPSessionManager cache policy
|
0
I had the same problem, and I did as you did, make Cache.onMemoryWarning() public and then call Shared.imageCache.onMemoryWarning() in the method didRecieveMemoryWarning().
And it worked!
Share
Improve this answer
Follow
answered Feb 1, 2016 at 12:04
RaptoXRaptoX
2,56522 gold badges1414 silver badges1515 bronze badges
Add a comment
|
|
I'm fetching about 136 images, each one about 500 KB, in order to have them cached on the disk.
After downloading image #98, I start getting the following error for the images left (which makes me think they aren't getting cached).
2015-07-29 09:52:44.471 MyProject[299:3418965] [HANEKE][ERROR] Failed to get data for key https://s3.amazonaws.com/my_bucket/my_image_n_99.jpg
Jul 29 09:52:45 my.host.net MyProject[299] <Error>: CGBitmapContextInfoCreate: unable to allocate 31492608 bytes for bitmap data
MyProject(299,0xb039f000) malloc: *** mach_vm_map(size=31494144) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
My first guess was the memory cache filled up, so I called HanekeSwift's Cache.onMemoryWarning() (had to make it public) since it has the following implementation:
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
But even tho I called it (and supposedly it should clear the memory cache), I still get the error, so I don't know what's wrong.
Any ideas?
|
HanekeSwift unable to allocate memory
|
0
Define a callback middleware as,
var storeResponseMiddleware = function(req, res, next) {
console.log("storing data in redis....")
..........more stuff
}
Add it to expressJs app as,
app.use(logicRoute)
app.use(storeResponseMiddleware)
Now, for all the responses storeResponseMiddleware will be called. you must call next() inside the route handlers.
Share
Improve this answer
Follow
answered Aug 10, 2015 at 1:34
user2879704user2879704
Add a comment
|
|
The scenario is to save the data in cache. We have numerous express routes written with complicated logic.
I have to find a way to save the response data in cache. I cannot go to each and every route and check whether this needs to be saved and save the data before sending the response. (If no other go, then this may be the way)
I have tried the following approaches.
https://nodejs.org/api/http.html#http_event_close_1 - using 'close' or 'finish', which fires after sending the response would do the trick. But there is no way I could get the response data in these events.
Also my node version is v0.10.31
Thought of using app.all('*', callback), but i am not sure how to catch the response data for cacheing.
Finally i thought of adding a second callback for routing, app.VERB(path, [callback...], callback), but upon returning the response in first callback, second callback is never called.
Hoping there is a solution for this, and I am stuck in this for more than a week.
The reason why adding logic into each and every routes is a tedious job is that, I need to add a configuration entry specifying which route needs to be cached with an expiry time.
Response needs to be cached in redis server. A cache key will be generated based on the route data and query strings. All those complete user specific information will be saved in a key.
So when the user hits the same route the key will be generated to check if it already exists using app.use and the data will be served without precedding to the successive middlewares.
|
ExpressJs execute a callback after sending a response for every route
|
0
In my opinion there is no need to do that for short keys. Hashing would be good if you're going to cache for example a long select query. It'll be better to keep 32 chars instead of long 200 chars. If you use hash for short key, you will have 32 chars instead of 7 or 10 chars.
Share
Improve this answer
Follow
answered Jul 1, 2015 at 7:54
ŁukaszŁukasz
63355 silver badges1212 bronze badges
Add a comment
|
|
I'm retrieving data from db and save it in cache under a key = user.id.1
I saw people using md5(key) or salt . md5(key) and advising to don't use stronger encryptions methods to don't add overhead.
If someone wants to access your cached data needs access to server, md5 is easily cracked these days, a salt seems to be pointless in this case and hashing the key will still not help with key collision if is the same key.
What's the reason to use a hash for the key?
Thanks
|
backend cache key really need being hashed?
|
I think this issue of caching files and replacing them with the unicode 'REPLACEMENT CHARACTER' (�) has to do with sendfile. Turn sendfile/EnableSendfile off in nginx/apache.
Related question is here: yeoman and angular utf8 issue and caching
|
Today I started changing some CSS on a Symfony (2.6) project. I added some styling to my newly created css file and everything was working fine. My problem occured when I went to add another style and nothing happened. I checked the dev window and couldn't find my styles anywhere. I've deleted the cache multiple times. Im using Symfony with a vagrant box. If I open the css file in the url it is filled with diamond/question marks and my first style entry is still there. I checked and the encoding is set to UTF-8. Ive never had issues like this with css, does anyone know what the problem could be?
I am using Assetic to include the style sheet within the project like this:
`<link href="{{ asset('css/print_production_report.css') }}" rel="stylesheet" type="text/css" media="print" />`
So to show you whats happening I'll start from the beginning. I had this stylesheet (ignore the error):
And upon checking the browser I still have:
Now when I add some random text or css to my stylesheet as so:
You will see that all my changes are being converted into these diamonds:
|
CSS changes not updating on site
|
0
You could achieve such a field based memoization by using the percflow Per Clause. This will create an instance of your aspect for each method that is woven.
This of course should only be used if the method has no parameter. when a method uses parameter, you'll still need a map to know what result to return based on the parameter.
Share
Improve this answer
Follow
answered Jul 26, 2016 at 13:04
XGouchetXGouchet
10.1k1010 gold badges4949 silver badges8383 bronze badges
Add a comment
|
|
I've seen some implementations of method result caching using AspectJ. For example, one in jcabi-aspects or some older examples.
The idea is that instead of writing bolierplate code for caching result of a method in a field, like this:
public Mesh someComplexGeometry() {
if (this.geometry == null) {
this.geometry = computeTheGeometry();
}
return this.geometry;
}
We annotate methods so AspectJ compiler changes their bytecode so that their result is stored somewhere after the first execution and retrieved on consecutive executions:
@Cacheable
public Mesh someComplextGeometry() {
// just compute the mesh, very neat and clear
}
My concern here is that all the implementations of caching aspects I've seen are based on storing values in a Map. It also involves a quite complex process of constructing keys for those maps. I'm afraid that it could have some performance implications.
I think it would be ideal if there was an aspect that worked this way: for each of n methods of a class that are annotated with @Cacheable, add a field private Object cache_n to that class, then at the first method invocation store the result in a field, not in a Map, and then keep returning the field contents on consecutive method calls.
So the idea is to inject custom private fields for each annotated method during weaving instead of using a whole fat Map. But I can't figure out how to do that and if it is even possible.
The following aspect implements what I want, but only for the case when a class only has a single method annotated with @Cached:
public aspect Cacher {
private Object cache;
pointcut cached(): execution(@Cached * * (..));
Object around(): cached() {
if (cache == null) {
cache = proceed();
}
return cache;
}
}
Can I do that kind of caching with AspectJ? If I can't, are there any platform restrictions that disallow such a thing, or is it just not implemented in AspectJ language?
|
Is it possible to implement method result caching based on field injection instead of a Map?
|
0
Cachecow specify caching policy. you can specify above by using below
[HttpCacheControlPolicy(true, 100)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Share
Improve this answer
Follow
answered Mar 10, 2016 at 3:12
Suresh ChahalSuresh Chahal
5488 bronze badges
Add a comment
|
|
I create asp.net webapi and try to use CacheCow but i can't set the Expiration time like CacheOutput
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
How can I do this with CacheCow ?
|
how to set CacheCow Expires for an action?
|
0
NB: iOS Safari and desktop Safari do not support service workers technology and there's no clear roadmap for it.
Since now in 03/2016 service workers have better browser support (Chrome, Firefox) I would recommend to use this functionality in combination with manifest.json.
What worked for me to provide complete offline experience is sw-precache. You can set it up as a build task (Gulp, Grunt) or run manually. As a result web app loads with UI even case even if the wifi is turned off in advance.
Main part is to add correct static files masks - check staticFileGlobs property in writeServiceWorkerFile function, smth like this:
staticFileGlobs: [
rootDir + '/css/**.css',
rootDir + '/',
rootDir + 'index.html',
rootDir + 'index.html/#/home',
rootDir + 'index.html/#/offline',
rootDir + '/img/**.*',
rootDir + '/js/**.js',
rootDir + '/locales/**.js'
],
Share
Improve this answer
Follow
edited Jun 14, 2016 at 11:28
answered Mar 23, 2016 at 11:16
shershenshershen
9,9151111 gold badges4040 silver badges6262 bronze badges
2
1
OP was asking about Mobile Safari, which unfortunately isn't supporting Service Worker any time soon.
– Changbai Li
Jun 14, 2016 at 9:32
1
UPDATE: August 3rd, 2017: Apple has changed their status for service workers from "under consideration" to "in development"! Please see this post for details.
– mesqueeb
Sep 11, 2017 at 4:29
Add a comment
|
|
I am trying to make a page mobile web app compatible be available offline on iOS devices. I have added the mobile web app compatible meta tag to the head of the document, and specified a cache.manifest file which contains all of the resources of the page.
I can see that the cache.manifest file is being used authoritatively to load the page resources (namely in the console I can see the resources being saved to the device when I first clear / load the manifest, and on subsequent page loads I can see the 'noupdate' event fires on window.applicationCache.
Despite this, when I turn off WiFi on the iOS device I am currently testing on (iPad 2nd gen, running iOS 8.3) I immediately get a message to say the page could not be loaded because the server cannot be found, the only options on this message are to retry (resulting in the same error) or to close the mobile web app.
Even though I get this error, I can see the page load behind the notification so clearly resources are still being fetched from the application cache, but as I say it appears that the 'no internet' message fires before any sort of application cache interation occurs.
Can anyone please advise as to how I may suppress this 'offline error' message, or fix the cache.manifest so that it works as expected, allowing me to use a mobile web app that is saved to homescreen, without being connected to the internet?
|
iOS Mobile Web App (via saving page to homescreen) offline availability
|
0
NSURLCache, which AFNetworking uses for caching, doesn't support caching this type of request.
You could try:
using SDURLCache, an open-source alternative that gives you more control, or
subclassing NSURLCache yourself to roll your own implementation
using requests that have supported caching headers
Share
Improve this answer
Follow
answered Apr 7, 2015 at 4:27
Aaron BragerAaron Brager
65.7k1919 gold badges163163 silver badges289289 bronze badges
2
Do you have any official document saying NSURLCache doesn't support?
– Hai Hw
Apr 10, 2015 at 17:32
from the NSURLRequest documentation: "If you are making HTTP or HTTPS byte-range requests, always use the NSURLRequestReloadIgnoringLocalCacheData policy. To learn more, read Caching Byte-Range Requests."
– quellish
Apr 11, 2015 at 7:43
Add a comment
|
|
I'm getting data from backend using AFNetworking and set request's cachePolicy as NSURLRequestUseProtocolCachePolicy.
The response headers contain ETag value and Transfer-Encoding is chunked.
In the second time I call the same API, it gets the fresh data instead of getting from cache as expected.
I notice that if the response is not chunked (contain Content-Length header), caching work perfectly
My question is: is it possible to cache chunked response in iOS?
Thank you for any advice
|
iOS - Is it possible to cache the chunked HTTP response?
|
0
If you open the Firefox network monitor you can click on the line where the file is loaded and view all headers etc.
Share
Improve this answer
Follow
answered Mar 24, 2015 at 11:42
Mike RatcliffeMike Ratcliffe
99766 silver badges1010 bronze badges
3
Thanks, but to give you a better idea of what I'm after, I'd love to be able to expand further information for each header and see the reason why it has been included in the request - a bit like how the "Computed" tab on the Inspector works for CSS, where you can see the logic behind why a particular attribute is being applied to the selected element.
– Pryo
Mar 24, 2015 at 12:58
Or put another way. Currently, if a request header doesn't appear when I expect it to, I need to try to guess why it's not there and try adjusting things to encourage it to appear. Either that, or read broadly around the whole subject to try to understand where I'm going wrong. This is frustrating because the browser will "know" exactly why it's not including the header, and I would just like it to tell me the reason (via some kind of debugger, or log file).
– Pryo
Mar 24, 2015 at 13:04
So you want some kind of network header troubleshooting tool that explains why e.g. a file is not cached? Sounds like something you should ask for on ffdevtools.uservoice.com
– Mike Ratcliffe
Mar 25, 2015 at 14:28
Add a comment
|
|
I am currently working on optimising the caching setup for a website. I have come up against a lot of situations where the cache headers sent from the server appear to be correct, but then my browser (Firefox in my case) doesn't issue the expected request headers on subsequent page loads. The logic the browser goes through to decide which request headers to send seems to be completely hidden.
Are there any development tools available that can, for instance, show clearly why Firefox (or any other browser) is, or is not, sending a "If-Modified-Since" header on a case-by-case basis? Or perhaps there is an advanced log I can activate on the browser that will report the steps it is going through. My current development workflow is a bit like trying to do coding without having access to any error reports or a debugger.
|
How to debug browser caching for web development
|
0
I had the same problem and after I rebuild web, restarted IIS and restarted my redis server - it took in account the setting in the timeout="123".
Share
Improve this answer
Follow
answered Nov 5, 2021 at 13:23
Martin ZalogaMartin Zaloga
12511 silver badge1010 bronze badges
Add a comment
|
|
I'm using RedisSessionStateProvider 1.6 and the following configuration:
<sessionState mode="Custom" customProvider="AzureRedisCacheSessionState" timeout="10">
<providers>
<add name="AzureRedisCacheSessionState" type="Microsoft.Web.Redis.RedisSessionStateProvider" ... />
</providers>
</sessionState>
But the 'timeout' value doesn't seem to work - whatever I put it just seems to use the default value of 20 minutes.
The session times out in 20 minutes (sliding), and Session.Timeout always returns 20.
This problem seems to be specific to version 1.6 - I tried installing version 1.5 instead and that works correctly.
I'm aware that there were some issues with the timeout being treated as absolute instead of sliding a couple of versions ago (I believe this bug was introduced in version 1.4 and fixed in version 1.5) - the issue I'm having is NOT the same.
|
Setting session timeout in RedisSessionStateProvider 1.6
|
0
A consistent copy of the cache on local disk provides many possibilities for business requirements, such as working with different datasets according to time-based needs or moving datasets around to different locations. It can range from a simple key-value persistence mechanism with fast read performance, to an operational store with in-memory speeds during operation for both reads and writes.
Ehcache has a RestartStore which provides fast restartability and options for cache persistence. The RestartStore implements an on-disk mirror of the in-memory cache. After any restart, data that was last in the cache will automatically load from disk into the RestartStore, and from there the data will be available to the cache.
Cache persistence on disk is configured by adding the sub-element to a cache configuration. The sub-element includes two attributes: strategy and synchronousWrites.
<cache>
<persistence strategy=”localRestartable|localTempSwap|none|distributed” synchronousWrites=”false|true”/>
</cache>
For more information Ehcache
Share
Improve this answer
Follow
answered Mar 4, 2015 at 22:31
SwathiSwathi
58055 silver badges1717 bronze badges
Add a comment
|
|
I am using Spring framework and Java CXF services.
There are several clients accessing a fixed list of data, which are fetched from Database. Since fetching from Database is an expensive call and DB doesn't change frequently, I thought it was good to cache value.
DB refresh -> 15 times a day at indefinite intervals
Cache refresh -> Every 15 minutes.
Cache loading by call to DB takes 15 seconds.
Now, If while Cache is refreshing by making a call to DB, it takes 15 secs. Within this 15 seconds, if clients wants to access data, I am OK to send the previous data in cache. Application is that Stale and Outdated data can be tolerated instead of waiting for 15 secs (there is a delta function which brings data after the time cache was loaded which is very inexpensive). Is there a way in ehcache to return old data in cache while the new data is being loaded while cache is refreshing at regular interval of 15 minutes?
|
Can ehCache return old cached value when cache is refreshing
|
0
A database read it's not really slow if you have constraints on the tables, but if you looking for minimize the database requests, 'caching' in database is not a solution (because you don't want other request).
I would like to suggest the use of Redis
Share
Improve this answer
Follow
answered Mar 14, 2015 at 19:06
nik.longstonenik.longstone
25422 silver badges88 bronze badges
Add a comment
|
|
Each user would be following different networks. The news feed consists of posts from different networks sorted according to rating. How can I design an effective cache system to minimize database read requests using memcached or any another software?
Website uses PHP and MySQL.
|
How to cache personalized news feed to minimize database read query?
|
I solved this with Tilt's cache mechanizm.
require 'tilt'
cache = Tilt::Cache.new
cache.fetch(path_of_your_file, Tilt.new(path_of_your_file,options))
this code will cache the Tilt object which includes the parsed version of your haml file. In my code cache key is the path of the file, you can give it whatever you want.
Forexample in development mode I'm using [path_of_file, mtime_of_file] so cache renews for that file whenever I modified the haml file.
|
I'm writing a simple web framework with ruby. I'm rendering my templates with
renderer = Haml::Engine.new(template_path, ...)
html_output = renderer.render(Object.new, params)
but this gives me only last rendered html output. Suppose that I have a view like this
-if title.include? 'Admin Page'
=title
-else
%a
Test
In every request it re-render html part of the template. Is there any way to get cachable version of this template for production to get rid of re-render. Caching pure html isn't enough here because title may change in request.
Firstly I thought this is impossible because result file must be ruby file and look like this.
output = ''
if title.include? 'Admin Page'
output << title
else
output << '<a>Test</a>'
end
but after a search I read that Haml files can be cached but I can't figure out how to achieve this. Can I cache Haml templates, if so how can I do this? Is my approach true in this concept or am I missing something?
|
How can I cache Haml templates inside ruby
|
0
I know it's a little bit late, but it might help others.
Give a try to https://github.com/rotorgames/angular-rg-cache-view
it seems to cache views while keeping the scope.
Share
Improve this answer
Follow
answered May 11, 2017 at 14:57
DccBrDccBr
1,2211414 silver badges1414 bronze badges
Add a comment
|
|
Angularjs cache compiled DOM element with scope
Context is I am working on the mobile environment,so i try to cache the compiled DOM element into memory like this:
cache[key] = $compile(myTemplate)(newScope);
and update the other element's content like this:
$('myElement').html(cache[key]);
the first time everything work well, and then i clear myElement's content and use the cache to update myElement's content again like this:
$('myElement').empty().html(cache[key]);
and the scope of the cached compiled template disappear(the scope of the cache[key]).
I don't want use:
$compile(myTemplate)(scope, function(compiledTemplate) {
cache[key] = compiledTemplate;
});
to compile template and apply to scope every time, so if there any way can cache the compiled Dom element with scope, please help me, Thanks.
|
Angularjs cache compiled DOM element with scope
|
I manage to find the solution using "haim770" guidelines.
The solution using the "Donut-Caching" (https://github.com/moonpyk/mvcdonutcaching)
1.first I get the "Donut Caching from the NuGet Packages.
2.I switched in the _layout.cshtml page the line : @Html.Partial("_LoginPartial") with @Html.Action("partialView", true)
3.Than I build an Action inside the Account controller called "partialView" that return the view I wanted, like this :
public ActionResult partialView()
{
return PartialView("_LoginPartial");
}
4.After it I decorated the Action that return the index page with
[DonutOutputCache(Duration=(60*60))]
like this:
[DonutOutputCache(Duration=(60*60))]
public ActionResult Index()
{
return View();
}
And you done, Thanks again to Haim(Chaim).
|
I'm trying to cache a page without the navbar of the page.
When i cache the page its all works fine but I get unwanted behavior.
Explanation:
When I cache the index page for example, the navbar is also cached so if the user press the log-in button and log-on, the user redirect to the same page (Index) and the log-in doesn't take affect (the user name and the log out button doesn't appear), the log-in and register buttons still shows, its a problem.
This is my code:
Home Controller:
public class HomeController : Controller
{
[OutputCache(Duration=(60*60))]
public ActionResult Index()
{
return View();
}
// ...
}
Can I do Vary by something to prevent it ?
|
Cache page without the navbar. User log-in/logout system doesn't update at all (MVC)
|
0
Sorry, can't comment, missing reputation.
You can try delete all -gzip occurrences in the ETag. That is what works for my custom caching mechanism. Actually, I was searching for a proper way to tell NSURLSession to use gzip ETags. This feels like a workaround.
Share
Improve this answer
Follow
answered Aug 21, 2019 at 9:06
lupdiduplupdidup
19188 bronze badges
Add a comment
|
|
I am trying to get NSURLCache to work on iOS8, but it seems to be broken when using an ETag and gzip compression. I am using NGINX with gzip compression enabled as a proxy for a thin webserver. The following response is not getting cached by NSURLCache:
HTTP/1.1 200 OK
Server nginx/1.7.6
Date Thu, 06 Nov 2014 14:28:50 GMT
Content-Type application/json;charset=utf-8
Transfer-Encoding chunked
Connection keep-alive
Vary Accept-Encoding
Cache-Control private, max-age=0
ETag W/"d693ff4d26d0e7f25498ecb89d8796cd41e9da4f"
Content-Encoding gzip
When I disable gzip in the NGINX config, the request is cached correctly:
HTTP/1.1 200 OK
Server nginx/1.7.6
Date Thu, 06 Nov 2014 14:26:40 GMT
Content-Type application/json;charset=utf-8
Content-Length 311433
Connection keep-alive
Cache-Control private, max-age=0
ETag W/"d693ff4d26d0e7f25498ecb89d8796cd41e9da4f"
I tried setting Cache-Control to public, but it did not help.
My setup with gzip enabled works perfectly on iOS7.
Does anyone have an idea what I am doing wrong? Or should I file a radar for this?
Thanks in advance
|
NSURLCache and ETags with gzip enabled are not working
|
I had the same issue. I would rename the file as countries.txt and serve it as text/plain mime type. On the client side you can parse the file as json.
|
Does App Cache work with files other than images and js/css/html ?
I'm trying to cache .json files which are later called via XMLHttpRequest on a url like
resources/data/countries.json, but the browser calls home and does not use the cached file.
Inspecting the App Cache with Chrome, I can see the file. Regular files (js/css/html/images) work as expected. No error is thrown during the caching/load process.
Is the reason this just doesn't work with App Cache or is it likely something else?
Thanks!
|
HTML5 App Cache for .json files?
|
0
I encountered the same problem. After a lot of research, I found that the way volley caches images on disk is according to the HTTP cache headers. If the cache headers say the image is still valid, then it will not be requested again from the server. And since the new image that you are storing has the same name, then volley will not request the image from the server. So, I applied this simple logic :
Lets say, initially your path of the picture is xxx.pic.jpg.
Obtain a random number, say x from any random number generator function. Simply append x to your profile picture path, i.e your new path of the image would be : xxx.pic.x.jpg. It should solve the problem :)
Share
Improve this answer
Follow
answered Jul 12, 2016 at 20:26
Tushar SahayTushar Sahay
1111 silver badge33 bronze badges
Add a comment
|
|
I'm working on an app where the user is able to change his profile picture which is actually being stored in server like this: http://serveraddress.com/user-pictures/user_id , the problem is that as volley uses an Image Cache even after the user has changed the profile image (its uploaded to server), the cached image is being display instead of the "updated" image.
I tried to remove the image from the cache, and also to invalidate the image URL (because it's the same), but it's not working.
getRequestQueue().getCache().invalidate("http://serveraddress.com/user-pictures/122432", true); //invalidate
mLRUCache.remove("http://serveraddress.com/user-pictures/122432");
I'd appreciate any suggestions.
Thanks in advance.
|
How to remove image from cache with Volley?
|
0
This turned to be a circular import in templates, not related to cacheops. Here is the issue.
To take home: circular imports provide lousy error messages in Python :)
Share
Improve this answer
Follow
answered Oct 7, 2014 at 6:48
SuorSuor
2,91411 gold badge2222 silver badges2828 bronze badges
Add a comment
|
|
Just installed django-cacheops. However, when I try to run python manage.py migrate or python manage.py syncdb, I get the following:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/south/management/commands/__init__.py", line 10, in <module>
import django.template.loaders.app_directories
File "/Users/stanleytang/Desktop/DoorDash/Development/doorstep-django/venv/lib/python2.7/site-packages/django/template/loaders/app_directories.py", line 25, in <module>
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
django.core.exceptions.ImproperlyConfigured: ImportError cacheops: cannot import name app_directories
I'm on django 1.6 and using django-cacheops 2.1.1
|
django-cacheops doesn't work with South
|
0
After much wailing and gnashing of teeth, I believe I've proven that this approach simply won't work on all browsers. Here's my experience thus far:
Firefox: Works a charm.
Chrome: Seldom works -- it's as though XHR uses a different cache than the elements (even though I'm pretty sure that's not the case; I haven't had time to delve into Chrome code to figure out exactly what's going on.
Safari: Apparently random. Sometimes resource requests kicked off from elements retrieve from the cache, sometimes not. I'm sure there's a method, but it appears to be madness from the outside.
In the end, I had to switch to the somewhat more craptastic-but-reliable approach of creating a hidden iframe, injecting script/img elements into it, then waiting on the iframe window's onload event. This works, but gives no fine-grained feedback in terms of which elements are loaded (getting reliable onload events from the individual elements is more "cross-browser tricky" than just waiting on the whole frame.
I'd love to understand more precisely what's going on in Chrome/Safari, but sadly don't have the time to dig in further.
Share
Improve this answer
Follow
answered Oct 8, 2014 at 18:35
Joel WebberJoel Webber
22211 silver badge88 bronze badges
Add a comment
|
|
I'm simply trying to use XHR to precache some resources, but the cache is not behaving as expected.
Here are the bounds of the problem:
I know the resource URLs in advance (of course).
I don't know their content-types (mix of CSS, images, and other).
They will always be same-origin.
I control the cache headers.
They can be cached forever for all I care.
I've always been under the impression that XHR used the browser cache more or less like any other resource, but never rigorously tested that. Here's what I'm doing:
Request all resources up-front with XHR.
Explicitly set request header Cache-Control: max-age=3600 (Chrome was setting max-age=0 for some reason).
Set the following response headers on the server:
Cache-control: public; max-age=3600
Date: now
Expires: now + 1 hour
[Content-Type, Content-Length]
Here's what I'm seeing:
XHR always fetches the resource (confirmed on server and with dev tools).
Subsequent requests (via image/css/etc elements) always fetch (even after the XHRs have completed) on a cold cache.
But they always use the cache when it's warm.
I've poked at it in various ways, but this behavior never seems to change.
|
Using XHR to precache resources not behaving as expected
|
the cache limit depends on the available system memory and on your worker process if running in 64 bits or 32 bits.
you will be able to use much more memory if running in 64 bits.
ASP.NET Cache will engage garbage collections and starts dropping cache when a w3wp process memory usage is greater than or equal to about 80% of the worker process memory limit.The worker process memory limit can be set in machine.config for aspnet_wp.exe, or in the IIS metabase for w3wp.exe.
|
I want to store up to 500 cache keys (one per user) using System.Web.Caching. The cached value wouldn't exceed an 11 character string (ie. 'Los Angeles')
string key = "Location" + userName;
string location = GetUsersLocation();
Cache.Insert(key, location);
Does this surpass the limitations of .NET caching or would this technique go against best practices?
|
What is the limit of .NET Cache keys I can store?
|
0
As answered also in the original question: CAS (Interlocked) operations have been (and most likely will be) the quickest caches flusher.
Share
Improve this answer
Follow
edited May 23, 2017 at 11:57
CommunityBot
111 silver badge
answered Nov 18, 2014 at 19:55
JanJan
1,94511 gold badge1717 silver badges4343 bronze badges
Add a comment
|
|
Is there a difference in timing of memory caches coherency (or "flushing") after Interlocked operations and after invoking Memory barriers? Let's consider in C# - using any Interlocked operations vs Thread.MemoryBarrier() - is the resulting memory caches refresh behavior identical or not?
I believe there is a difference. I was solving one business case that seemed to be caused by delayed flush after memory barrier (we replaced with Interlocked operation). Also there is quite a few information sources (including wikipedia) suggesting that memory barriers doesn't guarantee timing of operations.
I can link more references or add example code snippet if interested, but initially I want to keep the question short (as I was down-voted for too much info in my original question to this topic)
|
Timing of memory caches coherency after memory barrier and after Interlocked operations
|
0
public function extractContent($content)
{
is the function in Enterprise_PageCache_Model_Processor that is supposed to extract content from FPC folder depending on request params.
Do some file write code within tis function code and log what content is returned.
if content is NULL then FPC is not working.
Share
Improve this answer
Follow
answered Oct 28, 2014 at 18:18
OscprofessionalsOscprofessionals
2,16122 gold badges1515 silver badges1717 bronze badges
Add a comment
|
|
We are using Magento 1.13 EE, memcache and APC op code cache.
Any text change made to the static cms page / static block is getting reflected immediately in the front end and in cache management FPC is showing the status as "enabled" and not as "invalidated".
Also the page load speed is slow. Seems FPC is not working. But every time the /var/full_page_cache/ folder is cleared, the folders gets rebuild and grows in size.
How to check whether the content is really rendered from FPC?
Could anyone please help on this.
|
Magento 1.13 FPC cache not getting invalidated
|
0
Right click on a folder in your project from Solution Explorer.
Choose Add Reference
Select System.Runtime.Caching
Share
Improve this answer
Follow
answered Aug 3, 2018 at 10:32
DreamTeKDreamTeK
33.3k2828 gold badges117117 silver badges176176 bronze badges
Add a comment
|
|
I have right-clicked on my project >> Properties >> Compile >> Advanced Compile Options >>
The target framework says .NET 4.0
Yet Visual Studio 2010 is not recognizing System.Runtime.Caching so I cannot start coding to improve performance of the web application.
Is this really not a .net 4.0 project? How can I confirm?
TY.
Imports System.Runtime.Caching
Dim dtContents As DataTable = New DataTable
dtContents = Session("Contents")
Dim cache As ObjectCache = MemoryCache.Default ??
cache.Item("cacheContents") = dtContents ??
|
System.Runtime.Caching not available in VB.net 4.0?
|
Assuming your cache-misses in a particular function are what is significant, then using either cachegrind or oprofile should work just fine. If your cache misses in that function are not significant for the whole execution of the program, why are you bothering?
From memory, but it was a couple of years since I used oprofile, but you don't need to restart the daemon, just using the "reset my data" (opcontrol --reset). Since oprofile is system wide, you can simply run a script with your multiple testcases - oprofile will split data per process, but if you have high cache-usage in any particular function, that should show up on the list of cache-misses. And if it doesn't show up, then your code isn't missing in the cache.
The way I've been doing it is to write a script that does the opcontrol --reset --start event=CPU_CLK_UNHALTED:400000, then whatever program I'm testing, and then opcontrol --stop --save=oprofile.result.
Note that oprofile is statistical and sample based, so you can't measure single cache-misses, and it records the address where the cache-misses counter reached the limit. So you can have a situation where, if you have a "limit" of 1000 cache misses, you get 999 cache misses in function A, and then a single cache miss in function B, function B is "credited" with the cache misses. However, assuming you don't have extremely pathological code, you will get your cache miss recordings in the areas of code that miss in the cache.
|
I want to profile the cache misses (rate) of a specific routine in a C++ program. I know some profiling tools but they don't seem to quite satisfy me.
To the best of my knowledge:
gprof can produce call graph and code coverage, but it doesn't include cache miss profiling.
valgrind (cachegrind) can profile cache misses but seems only for the whole application.
oprofile indeed has a symbol-based output. But I'm a bit confused: say if procedure A() calls B() (maybe library or system call), and cache misses occur inside B(), is it attributed to A()? After all I would like to count the cache misses during the whole execution of A().
A last question. OProfile requires restarting the daemon for each new session. Suppose I want to profile my program with a number of runs --- with a set of different parameters and inputs. How can I do it in an automated way? Is there some way like inserting gettimeofday() into the code to get the cache statistics?
|
Profiling cache misses of a routine
|
I didn't manage to find a natural solution to this issue. In the end because I needed to move forward, I just added a certain tag in the query string, e.g. {ASSETS_VERSION}, and then I search/replace this with the revision number of the project at deployment time as part of my deployment script.
I'm not proud of this solution but it did solve my problem in the short term until I can find a more elegant solution.
|
I have a web site built on Symfony2 which uses twig templates, LESS, and assetic.
In order to cache bust assets, I'm simply using this in my config.yml:
framework:
templating:
engines: ['twig']
assets_version: 'asset-version-here'
And then I use the asset() function to load the asset and the cache busting is handled for me.
However, the concern I have is when I load my LESS (css) file, there are references to other files, and I would like to know how these files can be cache busted as well.
Example:
.someSelector { background:url('../images/filename.png'); }
How can I make sure that the referenced file, filename.png is cache busted upon deployment?
The asset files referenced in Twig using asset() are cache busted automatically upon deployment (I use a deployment script hook that updates the assets_version in the framework's config), but those referenced in a stylesheet are not.
How can I do this?
|
How can one cache bust files referenced in a LESS file when using Symfony2, Twig, and Assetic?
|
Just figured out the solution.
I Disabled all the breakpoints in my script and then reloaded, it takes up my latest changes.. Woohoooo :-)
Don't know why it does that but it fixed my problem. Perhaps, in order to maintain those breakpoints, it was not refreshing my js files.
|
For web development, I have disabled cache in Chrome -> Dev Tools -> Setting -> General -> Disable Cache.
However, when i refresh my site, it doesn't reflect my changes which is super annoying.
I have to manually empty the cache.
What is there that I might be doing wrong?
Note: I close my dev tools when i refresh as suggested here: Disabling Chrome cache for website development
|
Web Development: Disabling Chrome's Cache doesn't work on osx
|
0
So to clarify, you have a load balancer for domain imgs.site.com passing along requests to port 80 on two machines. Each of these is running varnish and routing requests back to themselves on port 82. If some new request gets routed to http server A, and then the same request comes in again later and gets routed to http server B, the second request will be as slow as the first and you'll end up with the same lookup cached on two machines, so you'd get better cache performance if you set up a single varnish and used it as your load balancer in a round-robin configuration.
But to solve it the way it is, you can get diagnostic information about how varnish is responding to a request by running varnishlog while the request comes in. You can further verify that a request from the varnish machine to its backend (in this case, itself) works by running from a shell on the varnish machine:
$ telnet 127.0.0.1 82
and if you see a success message, enter a basic GET command (with two returns afterward):
GET / HTTP/1.0
You can test more complex requests requiring authentication or POST payloads using wget or curl commands.
And of course, verify that the http server is receiving the request by checking the logs.
Share
Improve this answer
Follow
edited Jun 27, 2014 at 19:48
answered Jun 27, 2014 at 19:28
jaybraujaybrau
41311 gold badge33 silver badges1010 bronze badges
Add a comment
|
|
We have 2 file servers(Apache port-82) which is running under Load Balancer. And I have configured varnish successfully for a domain(imgs.site.com) in 2 servers(port-80) and its working properly when i put a host entry for the server but when i access it globally(through LB) it went Aborted request. I guess there is something missing in my configuration. Pls help.
Here is my vcl configuration and i have the same configuration in both file1 and file2 servers
backend default {
.host = "127.0.0.1";
.port = "82";
.first_byte_timeout = 60s;
.between_bytes_timeout = 60s;
}
sub vcl_recv {
if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
req.request != "TRACE" &&
req.request != "OPTIONS" &&
req.request != "DELETE") {
return (pipe);
}
if (req.http.host == "imgs.site.com") {
set req.http.host = "imgs.site.com";
set req.backend = default;
return (lookup);
}
}
It may be a basic question and since we're new to varnish, we dont know how to solve it.
|
Varnish under LB server
|
You can use HTML5 Application Caching in remote website and load it in the app using Cordova InAppBrowser, so that when you click on a game, it opens a InAppBrowser and loads the game from webserver, this game can have the manifest with application cache, so that all content is downloaded on the device and launched.
You can develop the main app using Intel AppFramework and load the list of games via a REST API from web server, clicking on game can open a InAppBrowser and load the Application Cached game webpage from web server. This can all be done in Intel XDK
Details on Application Cache can be found here
|
I'm starting an uphill journey developing a small app for my wife's speech pathology practice. We want to publish an app that contains several html5 based games that promote language development. Currently I'm looking at the intel app framework and xdk to do this. We plan to start with a simple game (building words for example) then adding more games over time.
My question is this, html 5 has a cache mechanism using a manifest. If I limit the games to a single page, can I store the games on a web server rather than forcing the user to download all of the content with the app at the time of install? The objective here is to allow games to be added without forcing updates of the app. I anticipate several Mb of sound clips and images per game.
Thanks in advance.
|
Offline caching with Intel app framework?
|
0
Memcached uses LRU (Least recently used) mechanism to determine which existing objects to expire when there are more number of objects to be stored than the space available. You can further refer to the following link to understand its mechanism for key expiry :
http://docs.oracle.com/cd/E17952_01/refman-5.6-en/ha-memcached-using-expiry.html
Share
Improve this answer
Follow
answered Mar 22, 2014 at 18:54
Chhavi GangwalChhavi Gangwal
1,17699 silver badges1313 bronze badges
Add a comment
|
|
I know that redis will expire the keys on its own, freeing the memory
and was wondering if memcached would behave the same.
Let's say I have a kind of cache keys that are expired very rarely
(we'll call them A), and another kind that expires every 5 minutes,
using Ruby on Rails' expires_in: 5.minutes (we'll call them B)
Will memcached drop the A keys if there are too many B keys ?
For instance if I can store 5 values in my store, a scenario could be:
Store A1 (4 values left)
Store B1 (3 values left)
Store B2 (2 values left)
Store B3 (1 values left)
Store B4 (0 values left)
At this point B1, B2 and B3 are expired (because their lifecycle is so
short).
What happens if I store another element in the cache ? Will it drop A1
since it's the oldest, or will it know that B keys are short lived and
use their spot in the memory first ?
|
What is memcached expiration behavior when keys have different time frames and the cache is full?
|
0
I think your parameters in findAll is incorrect.
It should be:
Bank::model()
->cache(1000, $dependency)
->findAll([
'select' => 'bank_id',
'order' => 'name ASC', // if it is in ascending order
'condition' => 'is_active = 1'
]);
I don't know what concatened so I just ignored it. But you can always use scopes for your conditions.
Share
Improve this answer
Follow
answered Mar 12, 2014 at 15:55
jhnferrarisjhnferraris
1,36111 gold badge1212 silver badges3434 bronze badges
Add a comment
|
|
I've a table containing more than 27,000 records. I want to fetch all data in Dropdown list. For that I've implemented cache but it seems to be not working as its getting very slow and showing blank page (Sometime browser is getting hanged).
Following is my code (I am using yiiboilerplate):
Configuration of backend/config/main.php in component array:
'cache' => array(
//'class' => 'system.caching.CMemCache',
'class' => 'system.caching.CDbCache',
'connectionID' => 'db',
),
In View page:
$dependency = new CDbCacheDependency('SELECT MAX(bank_id) FROM bank');
$bank = CHtml::listData(Bank::model()->cache(1000, $dependency)->findAll('is_active=1', array('order' => 'name')), 'bank_id', 'concatened');
echo $form->dropDownListRow($model, 'bank_id', $bank, array(
'empty' => 'Select'
));
I think 27000 records is not big data but still its getting very slow and I want to implement cache in my entire application.
Is my configuration correct? Where I am going wrong?
Thanks
|
Query caching not working in Yii framework
|
0
I just ran into this same problem. This isn't necessarily simpler, but if you were planning to upgrade to Rails 4 anyway, you can simply override this method in your model:
private
def timestamp_attributes_for_update
super << :last_modifed_time
end
Unfortunately, as you discovered, since Rails 3 hardcodes the :updated_at value in cache_key, this solution doesn't work. However, this is fixed in Rails 4.
Share
Improve this answer
Follow
answered Mar 3, 2014 at 20:43
dgrossdgross
36911 silver badge1212 bronze badges
Add a comment
|
|
Am using Rails 3.2.13.
We use last_modified_time as our last updated column. My problem is that when i do model.cache_key it does not take into account the :last_modifed_time column.
Current (Rails 3.2.13) implementation in Rails:
# Returns a cache key that can be used to identify this record.
#
# ==== Examples
#
# Product.new.cache_key # => "products/new"
# Product.find(5).cache_key # => "products/5" (updated_at not available)
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
def cache_key
debugger
case
when new_record?
"#{self.class.model_name.cache_key}/new"
when timestamp = self[:updated_at]
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
else
"#{self.class.model_name.cache_key}/#{id}"
end
end
Am overriding it in my model like this:
def cache_key
updated_at = self[:updated_at]
if self.last_modified_time && !updated_at
timestamp = self.last_modified_time.utc.to_s(cache_timestamp_format)
"#{super}-#{timestamp}"
end
end
My question is: is there a simpler way to override the :updated_at to get the correct cache_key ?
|
Rails override updated_at with another column to get correct cache_key
|
I know the well known Instrumentation Java method is unable to correctly calculate the deep size of an object.
With Instrumentation alone, no.
With instrumentation and a knowledge of how the memory of a particular JVM is laid out will give your number of bytes used. It won't tell you how other JVMs might work and it doesn't tell you how much data is shared.
Is there a reliable way to compute on the JVM the correct deep size of an object?
I use a profiler, but unless you believe some of the tools you use you can never know.
The use case I'm thinking about is a fixed (or upper bounded) memory size data structure, i.e. a cache.
How slow are you willing to make your cache for precise memory usage? If it is 10x or 100x slower but has very accurate usage is this better than something which just counts the number of elements?
so either a "standard" coding practice or a well tested library
In that case, use the element count. You can use LinkedHashMap or ehcache for this.
|
This question already has answers here:
How to determine the size of an object in Java
(29 answers)
Closed 10 years ago.
as far as I know the well known Instrumentation Java method is unable to correctly calculate the deep size of an object.
Is there a reliable way to compute on the JVM the correct deep size of an object?
The use case I'm thinking about is a fixed (or upper bounded) memory size data structure, i.e. a cache.
Note: as far as possible, I would like an enterprise-ready solution, so either a "standard" coding practice or a well tested library
|
JVM deep memory size of an object [duplicate]
|
Use ICacheProvider instead.
OutputCache is very limited on what you can do.
Once you need to change the data that is cached, you can invalidate that particular data using ICacheProvider while using OutputCache, you either cache the entire ActionResult or none.
Also OutputCache does neither have the flexibility that ICacheProvider has, nor the beauty of working with it.
|
I am trying to implement caching in an MVC 4.0 ASP.net application. I can cache using outputcache
[OutputCache (Duration=60)]
public ActionResult myaction(string parm1)
{
--logic to construct the model object
-- followed by this return statement
return PartialView(model);
}
But I need to clear the cache after editing data which is stored in an xml file.
So I tried to add
HttpResponse.RemoveOutputCacheItem(Url.Action("myaction", "myController"));
in another action of the same controller before calling return RedirectToAction(myaction);
But the cache is not getting reset.
Is this the method to refresh outputcache using actions? I call these actions from jquery using ajax.
|
MVC 4.0 Clearing output cache using HttpResponse.RemoveOutputCacheItem
|
0
Well, I saw some syntax errors in your code (maybe you didn't copy the code but typed it manually for SO not sure). Also you returned deferred instead of deferred.promise. What you trying to achieve works just fine:
Plnkr Example
Share
Improve this answer
Follow
edited Jan 19, 2014 at 19:35
answered Jan 19, 2014 at 19:26
Alexander KalinovskiAlexander Kalinovski
1,40911 gold badge1313 silver badges1919 bronze badges
2
Thanks a lot! I will make some corrections to the post, I did type it in directly :) Wonder why thats not the behaviour I get locally... Im not sure if the navigation back and forth that is causing the trouble can be replicated in a plnkr?
– acrmuui
Jan 19, 2014 at 19:40
Well, you can get back and forward. It still works fine for me in plnkr.
– Alexander Kalinovski
Jan 19, 2014 at 19:43
Add a comment
|
|
I have a basic app, that fetches some data through the $http service, however it doesnt render the data correct in the template, when the template is served from the template cache. My code looks like this:
angular.module('app', [])
api service:
.factory('api', function($http, $q) {
return {
getCars: function() {
return $http.get('api/cars');
}
};
})
the controller using the service:
.controller('carsCtrl', function($scope, api) {
api.getCars().success(function(data) {
$scope.cars = data;
});
})
the route setup:
.config(function($routeProvider) {
$routeProvider.when('/cars', {
templateUrl: 'cars.html',
controller: 'carsCtrl'
});
});
and the template cars.html
<div ng-repeat="car in cars">
{{ car }}
</div>
this works the first time the browser hits /cars, however, if I push the back on forward button in the browser to hit the url a second time without a page reload, the {{car}} is not being rendered. If the cars.html is put in the templateCache like this:
angular.module('app').run(function($templateCache) {
$templateCache.put('cars.html', '<div ng-repeat="car in cars">{{ car }}</div>');
});
the .factory('api', function($http, $q) {
return {
getCars: function() {
return $http.get('api/cars');
}
};
})
0 binding is not rendered either.
I suspect this has something to do with Angular not unwrapping promises in templates anymore, but not totally sure. Does anyone know what I am doing wrong and how to write this code correctly?
|
Templates from templatecache not rendering bindings when data is returned from $http in 1.2+
|
0
It sounds like you have a couple of different types of issues here with your current setup.
1) I don't have a good answer for this because I don't actually know much about rest clients in .net. You also may also get better results if you change your architecture as mentioned below.
2) It looks like the problem you have here is that you're just storing the raw request object(RestValue) in the IMap rather than storing the content of that object. Usually requests to a rest api contain more information than just the value sent to your server so you'll have to extract the value from the RestValue in your rest api. Hazelcast RestValue has a method called getValue(), so you should just be able to call getValue() which returns a byte[]. You should then just convert that byte[] to a String (or whatever datatype you prefer to store, maybe RestValue0 in this case) and store the result in your RestValue1 instead of just storing the entire RestValue2 object.
As far as having .net + java architecture, it may be best to run a Hazelcast-server node in whichever language you prefer and then have a .net hazelcast-client node and a java hazelcast-client node that are all connected to the same cluster. This way you can have all of your .net code run on your .net client completely separattd from your java infrastructure and communicate between the separate languages using hazelcast.
Share
Improve this answer
Follow
answered Nov 23, 2015 at 20:32
DrewDrew
41644 silver badges1313 bronze badges
Add a comment
|
|
I want to use Hazelcast in my Java application, but I also have .net applications which need to get/set data to/from the Hazelcast cache. I thought to use the "rest" approach. I have 2 questions:
1) How can I post and get a complex type? If I have a Person object with fields name (String), age (Integer), birthDate (Date), and sex (Enum), how should I post this info and how should I parse person info?
2) I have a cached IMap<String, String>. After I post data "three" with key "3" from a Poster plugin, on the Java side map.get("3") returns something like:
RestValue{contentType='text/plain;charset=utf-8', value="three"}"
I expect this code to return just "three" without any cast operation.
I will be pleased if you give information about this issues.
Thanks in advance...
|
How to use Hazelcast with restful?
|
0
I've done a fair amount of experimentation with browser cache control, and I am surprised that no one has posted an answer.
Many people do not pay attention to this. As a results websites--for no reason at all--make browsers perform useless roundtrips for a 304-not modified on images, js or css files which are unlikely changed in 5 years--like who is going to change jquery.v-whatever?
So anyway, I have found that when you hard refresh the browser using F5 or ctrl-r, Chrome will revalidate just about everything on the page--as it should. This is very helpful and is why you want keep the etags in the response header.
When testing your max-age and expires headers, browse the site as a user naturally would by clicking the links on the page. Watch the web server's logfile (I use http://www.apacheviewer.com) and you'll get a good idea of how the browsers are caching.
Setting the headers works. I posted this a while back: Apache: set max-age or expires in .htaccess for directory
The easiest way for me to manage the web server is to create a /cache directory and instruct apache to set a 1 year max-age and expires header for everything in every subdir.
It works wonders. My pages make 1 round trip to the server, where as they used to make 3-5 trips with each request, just to get a 304.
Write your html as you normally would. The browsers will obey the cache settings in the headers.
Just know that hard refreshing the browser causes the browser to ignore max-age and relies on etags.
Share
Improve this answer
Follow
edited May 23, 2017 at 12:03
CommunityBot
111 silver badge
answered Jan 18, 2014 at 3:02
Brian McGinityBrian McGinity
5,82755 gold badges3737 silver badges4646 bronze badges
Add a comment
|
|
I am trying to learning the browser's (Chrome/Firefox) cache mechanism.
I set up a simple HTML:
<HTML><BODY>
Hellow World
<script>
function loadJS(){
var s = document.createElement('script');
s.setAttribute('src','/myscript');
document.body.appendChild(s);
}
loadJS()
</script>
<BODY></HTML>
I output "Cache-Control: max-age:30" for "/myscript"
Everytime I press F5, browser will re-validate /myscript with my server to get a 304 back.
But if I use
setTimeout(loadJS, 1);
Everytime I press F5, it looks like browser will check expire time, and if not expired, browser will use the cache directly instead of going to server for revalidation.
My question is:
Why? is there a detail explanation for this?
Does it mean if I want browser to use cache and reduce network request as much as possible, I need to wait the page loaded, and then request resources by js later?
|
Browser used cache without revalidate
|
0
I think this link might help you. You can use getCacheDir() for caching your video files. They will be stored in the internal storage of the app.
Share
Improve this answer
Follow
answered Dec 16, 2013 at 9:04
Bhavin ParmarBhavin Parmar
3366 bronze badges
Add a comment
|
|
I am developing an android application in which users can see the list of the videos in our database. All the videos are saved in Ooyala video platform.
Now when the user clicks on "download video" button, that video needs to be saved in the application cache. The user can view the video later at anytime. But I need it to be downloaded in the application cache itself, not in the library, so that the user can share that video easily.
So I created a local dababase in the application and saved the video lists.
But I am stuck here, in saving the cache area.
|
Cache the video in Android application
|
0
From personal experience I can tell you CloudFront invalidations don't take that long. Because your users may leave your page open for a long time, you need to deal with multiple versions of your application running at the same time anyway.
Here's a Bash script to invalidate using the AWS CLI and wait for the invalidation to propagate:
# Invalidates the CloudFront cache,
# waits for invalidation to be propagated.
function invalidate_cache() {
local invalidation
local invalidation_id
local distribution_id=$1
local status=""
invalidation=$(aws cloudfront create-invalidation --distribution-id "$distribution_id" --paths '/*')
invalidation_id=$(jq -r .Invalidation.Id <<< "$invalidation")
while [[ $status != "Completed" ]]; do
echo "Waiting for CloudFront invalidation to complete..."
sleep 1
status=$(aws cloudfront get-invalidation --distribution-id "$distribution_id" --id "$invalidation_id"| jq -r .Invalidation.Status)
done
}
If for some reason you always want to make sure index.html is fresh, then simply have CloudFront not cache it at all. You can create a specific CloudFront behavior for /index.html and override the time-to-live to zero.
Share
Improve this answer
Follow
answered Nov 16, 2018 at 15:38
djanowskidjanowski
5,73011 gold badge2828 silver badges1717 bronze badges
Add a comment
|
|
I'm pointing a CloudFront distribution to my BackboneJS app. This includes index.html, master.css, master.js.
Steps:
Append ?v=ID to css & js links within index.html
Deploy index.html, css, js files to origin server.
Invalidate index.html file @ CloudFront
Wait for CF to grab new index.html file from server and load the newly versioned assets.
When I deploy, I can bust the master.css and master.js cache by applying a new querystring within the index file. Unfortunately the index.html file cache has to be manually invalidated - a process which Amazon says can take 10-15minutes.
Any tips to instantly change index.html file to latest version on CF?
Thank you!
|
Invalidating cache for backbone index.html on CloudFront
|
0
Short: apc_store() should be slightly slower than apc_add().
Longer: the only difference between the two is the exclusive flag passed to apc_store_helper() that in turns leads to the behavior difference in apc_cache_insert().
Here is what happens there:
if (((*slot)->key.h == key.h) && (!memcmp((*slot)->key.str, key.str, key.len))) {
if(exclusive) {
if (!(*slot)->value->ttl || (time_t) ((*slot)->ctime + (*slot)->value->ttl) >= t) {
goto nothing;
}
}
// THIS IS THE MAIN DIFFERENCE
apc_cache_remove_slot(cache, slot TSRMLS_CC);**
break;
} else
if((cache->ttl && (time_t)(*slot)->atime < (t - (time_t)cache->ttl)) ||
((*slot)->value->ttl && (time_t) ((*slot)->ctime + (*slot)->value->ttl) < t)) {
apc_cache_remove_slot(cache, slot TSRMLS_CC);
continue;
}
slot = &(*slot)->next;
}
if ((*slot = make_slot(cache, &key, value, *slot, t TSRMLS_CC)) != NULL) {
value->mem_size = ctxt->pool->size;
cache->header->mem_size += ctxt->pool->size;
cache->header->nentries++;
cache->header->ninserts++;
} else {
goto nothing;
}
The main difference is that apc_add() saves one slot removal if the value is already present. Real world benchmarks would obviously make a lot of sense to confirm that analysis.
Share
Improve this answer
Follow
answered Jul 5, 2014 at 21:46
Lars StrojnyLars Strojny
66744 silver badges1111 bronze badges
Add a comment
|
|
While I understand the differences between apc_store and apc_add, I was wondering if using one or the other has any performance benefits?
One would think apc_store COULD be a bit quicker since it does not need to do a check-if-exists before doing the insert.
Am I correct in my thinking?
Or would using apc_add in situations where we know FOR SURE that the entry does not exist prove to be a bit faster?
|
Any performance benefits of using apc_store vs apc_add (or vice versa)?
|
0
Like others have said, this is a pretty broad question, and I believe it really depends from browser to browser. More often than not, your browser will cache things like images, css, and js files to reduce page load times when visiting the site again.
If you're worried about your audience being able to view your new content or functionality, one 'easy' method is to version your js and css files. This can be done by doing something like this:
script type="text/javascript" src="someplace/main.js?ver=1.5" >
Notice the ? after the js extension. This simply tells the browser that there is more data to process. If it does not recognize the string, it will attempt to download the file again, thus, updating your client side cache.
Share
Improve this answer
Follow
answered Oct 3, 2013 at 2:00
user2301366user2301366
111 bronze badge
Add a comment
|
|
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 years ago.
Improve this question
I was wondering how browsers determine when to fetch a script from the server vs from the cache...
When developing, I never have to clear my cache to see changes. However, some people often experience problems with their browser caching scripts and not fetching a newer version. I know you can append a query string to the filepath to force it to fetch from the server, but in this question I'm more interested in understanding the mechanics behind the problem. Why does the cache interfere only sometimes and why does it not effect everyone the same?
Also, how might this differ from browser to browser? IE, Firefox, Chrome, etc...
Thanks
|
How does client-side caching of JavaScript work? [closed]
|
0
I updated Rails from 4.0.0 to 4.0.2 and the cache digest appears to be working correctly!
Share
Improve this answer
Follow
answered Dec 20, 2013 at 22:10
Tom RossiTom Rossi
11.8k66 gold badges6767 silver badges9797 bronze badges
Add a comment
|
|
I'm likely doing something silly, missing a step, or something, but I can't seem to make digest caching work the way I believe it should.
My understanding is that, in rails 4, doing this:
- cache ['v1',@article] do
= render :partial => "show_article", :locals => { :article => @article}
Should build a cache digest that includes an MD5 of the view. And I see something like that in my logs:
Write fragment views/v1/articles/198-20130904195924000000000/2c68729b145522780d64dee67957c0e3
But, if I later change show_article.haml:
%h2 This should change the view's MD5.
Then reload the same page, I get:
Read fragment views/v1/articles/198-20130904195924000000000/2c68729b145522780d64dee67957c0e3
instead of a fresh render. Isn't the whole idea of digest caching that I DON'T have to update the "v1" string every time I edit a view file?
Or am I misunderstanding this?
This is made all the more difficult because in Rails 3 I could do this when using the cache_digests gem:
rake cache_digests:nested_dependencies TEMPLATE=articles/show
But that rake task doesn't exist in rails 4, even though the cache_digests gem is now part of it.
|
Rails 4: Cache digest doesn't change cache_key when I update view
|
You should probably use a View for each of your Pivot
From MS documentation
After a unique clustered index is created on the view, the view's
result set is materialized immediately and persisted in physical
storage in the database, saving the overhead of performing this costly
operation at execution time.
|
My problem is that in our application we do complex SELECT on our MS SQL Server (2008) database which is made up of several joins (3 and more) to be used between the tables created using PIVOT (every pivot table has about 10 000 rows).
Only a SELECT is quite fast (select returns only a few rows from the total as 50 from 10, 000). But finding count of all records with Count(*) or filtering is much slower (for 10 000 records about 2 seconds)
Is there any way to speed up queries on the total number of queries and on filtering?
For example some caching in SQL Server or optimalization query?
Note: query to database made by our ASMX service.
Note2: Every table, which contains pivot has primary key type: uniqueidentifier
Base select looks like this:
SELECT
Table1.[Id] AS [Id],
Table1.[Status] AS [Status],
Table2.[Id] AS [Id],
Table2.[Status] AS [Status],
FROM
(
-- Do PIVOT
) AS Table1
LEFT JOIN (
-- Do PIVOT
) AS Table2 ON Table2.xxx = Table1.yyy
)
--Catch only first X records..
|
Faster count(*) with pivot tables
|
0
try something like this with lock object.
static readonly object objectToBeLocked= new object();
lock( objectToBeLocked)
{
if (HttpContext.Current.Cache["GenRebateDiscountPercentage"] == null)
{
IShoppingService service = ServiceFactory.Instance.GetService<IShoppingService>();
rebateDiscountPercentage= service.GetGenRebateDiscountPercentage().Result;
if (rebateDiscountPercentage > 0)
{
HttpContext.Current.Cache.Add("GenRebateDiscountPercentage", rebateDiscountPercentage, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
else
{
decimal.TryParse(HttpContext.Current.Cache["GenRebateDiscountPercentage"].ToString(), out rebateDiscountPercentage);
}
}
Also you can look into following thread.
What is the best way to lock cache in asp.net?
Share
Improve this answer
Follow
edited May 23, 2017 at 12:26
CommunityBot
111 silver badge
answered Jun 11, 2013 at 13:02
Jalpesh VadgamaJalpesh Vadgama
14k2020 gold badges7373 silver badges9494 bronze badges
Add a comment
|
|
I have a static method in a helper class named helper.getdiscount(). This class is ASP.NET frontend code and used by UI pages.
Inside this method I check if some data is in the ASP.NET cache then return it, otherwise it makes a service call and store the result in the cache and then returns that value.
Will this be a problem considering multiple threads might be accessing it at the same time?
if (HttpContext.Current.Cache["GenRebateDiscountPercentage"] == null)
{
IShoppingService service = ServiceFactory.Instance.GetService<IShoppingService>();
rebateDiscountPercentage= service.GetGenRebateDiscountPercentage().Result;
if (rebateDiscountPercentage > 0)
{
HttpContext.Current.Cache.Add("GenRebateDiscountPercentage", rebateDiscountPercentage, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
else
{
decimal.TryParse(HttpContext.Current.Cache["GenRebateDiscountPercentage"].ToString(), out rebateDiscountPercentage);
}
Please advise if this is fine or any better approach could be used.
|
Read and write to ASP.NET cache from static method
|
0
Do your FooService and ContentService really need to behave in a transaction? If not, try disabling the transactional behavior of the services by adding the line below to your service classes and see if it helps:
static transactional = false
Share
Improve this answer
Follow
answered May 9, 2013 at 19:16
TriTri
52822 silver badges66 bronze badges
Add a comment
|
|
I have a service that I'd like to make cacheable. I've been looking into the grails-cache plugin and it looks very promising, but it's causing some behavior that I don't understand.
Consider the following service:
class FooService {
def contentService
@Listener
void processFoo(Foo foo) {
doStuff(foo)
foo.save(failOnError: true)
}
private void doStuff(Foo foo) {
contentService.evaluate(foo.name)
}
}
Now here's the ContentService definition:
class ContentService {
Object findSource(String name) {
Content.findByPath(name) ?: Content.findByPath(stripLocale(name))
}
String evaluate(String name) {
....
}
}
This all works fine until I try to add caching. First, I set it up in Config.groovy:
grails.cache.config = {
cache {
name 'content'
}
}
Then in my ContentService, I annotate my method:
@Cacheable('content')
Object findSource(String name) {
Content.findByPath(name) ?: Content.findByPath(stripLocale(name))
}
After making these changes, my processFoo method successfully executes every line of code and then throws one of these on exit:
illegal arg invokation java.lang.reflect.InvocationTargetException
org.springframework.transaction.UnexpectedRollbackException:
Transaction rolled back because it has been marked as rollback-only
What confuses me the most about this is that the method with the @Cacheable annotation isn't even called by my FooService. Only the evaluate() method is called, and there appear to be no issues with that method. Why would adding this annotation to a method that's not even being used in this execution cause the transaction to rollback?
|
Why does turning on @Cacheable cause my transaction to fail?
|
0
Clear cache:
// clear cache
super.clearCache();
super.loadUrl("file:///android_asset/www/index.html");
Source:
Adding a splash screen and clearing cache with PhoneGap and Android
Share
Improve this answer
Follow
answered Jun 18, 2014 at 13:33
Richard MuthwillRichard Muthwill
32733 silver badges1717 bronze badges
0
Add a comment
|
|
I'm developing a app with PhoneGap/Cordova 2.5.0 and I'm making AJAX calls with jQuery 1.8.2 to retrieve datas from an external server. I'm doing a lot of requests and I can see my app cache growing up, and this is not pretty cool...
I've tested many things like :
$.ajaxSetup({
cache: false,
headers: {
"Cache-Control": "no-cache"
}
});
OR / AND
var ajaxRequests = {}; // Limit one AJAX call for each "data_id" to prevent numbers calls
if (vrbd.ajaxRequests[data_id] === undefined) {
ajaxRequests[data_id] = $.ajax({
type: 'GET',
dataType: 'xml' + data_id,
url: url,
data: {
_: new Date().getTime() + Math.random()
},
async: true,
timeout: (data_count >= 2 ? data_count * 800 : 2000),
cache: false,
headers: {
"Cache-Control": "no-cache"
}
})
.done(function(data, textStatus, jqXHR) { ... })
.fail(function(jqXHR, textStatus, errorThrown) { ... })
.always(function(jqXHR, textStatus) { delete ajaxRequests[data_id]; });
}
If I let my app running during a couple of hours, I can see my cache growing up from about 160kb to about 30Mb in Settings > Apps > MyApp > Cache (AVD and real device).
So, didn't I understand anything about the cache in Settings or did I forget something ?
Please, let me know if you need another informations, sorry for my english, and thanks in advance for your help.
Best regards
Alex
|
PhoneGap Android cache app
|
If the session is reset, which can be caused by things like updating the web.config, modifying the dlls, even automatic app pool recycling by IIS, will cause your sessions to get cleared. If you have more than one web server you'll have to worry about syncing the sessions across the multiple web servers and the one in the database as well. Personally I try not to store anything in the session where it can be avoided.
|
I'm building a website to allow users to create a schedule composed of several tasks.
The schedule and task information are stored in a database.
When creating a schedule, the user can add, edit or remove as many tasks as they want before finally saving the schedule. These changes are persisted to the database so that the user can resume editing at a later point (if their session ends unexpectedly or they get interrupted).
Every time a request comes in to update a task, the website calls the appropriate method from my data access layer, then re-requests the entire schedule dataobject from the database to display to the user.
This seems like overkill when only a task is being edited. I want to cache the schedule object and its task list in HttpContext.Session and only update the individual task being changed (or the schedule object when it's changed).
Are there any dangers with my two versions getting out of sync, as long as I only update my cached object when I get confirmation that the edit operation was successful?
|
How should I cache a complex object being built in ASP.NET MVC?
|
I assume you are getting at this, System.Runtime.Caching, similar to the System.Web.Caching and in a more general namespace.
See http://deanhume.com/Home/BlogPost/object-caching----net-4/37
and on the stack,
is-there-some-sort-of-cachedependency-in-system-runtime-caching and,
performance-of-system-runtime-caching.
Could be useful.
|
I understand the .NET 4 Framework has caching support built into it. Does anyone have any experience with this, or could provide good resources to learn more about this?
I am referring to the caching of objects (entities primarily) in memory, and probably the use of System.Runtime.Caching.
|
Built-in Cache Interface in .NET [duplicate]
|
0
No, there's no way to prevent the browser from storing the files in cache. no-cache instructs the browser to not use a stale version of the file, but it doesn't prevent it from storing the file.
Share
Improve this answer
Follow
answered May 29, 2014 at 22:55
svpinosvpino
1,9241717 silver badges1818 bronze badges
Add a comment
|
|
I wonder if there is a way to tell browser NOT to put entries of particular files in cache. I know that I can just send headers like no-store, Expires etc., but all those cause the entry to appear in cache anyway, though with past date.
I would like to know the solution that nothing appears in cache - I just don't want to litter the browser memory with hundreds of stale entries. For example, I don't want to cache png, so I use no-store no-cache, and in "about:cache" I see lots of information about this file, together with expiration date 1970-01-01 01:00:00. I would prefer not to see anything there with png extension, because I create hundreds of them in each session and they are needed only once, so I don't want to fill the cache with this junk.
I think that "no-store" should really not store, and instead it stores, but with past date!
|
How to really "no-store" files in cache
|
0
I implemented a solution to warm up a cache after a CMS Block is saved. You may take the inspiration of this solution to do the same for different cases (product save, CMS block, CMS Page, Category Save, etc)
This piece of code can be triggered after a CMS Block save by using an observer cms_block_save_after:
/**
* Clean targeted cache block and warmup if content is provided
*/
public function clearBlockHtmlCache(Varien_Event_Observer $observer)
{
$block = $observer->getEvent()->getObject();
$id = $block->getCacheKey();
// Remove only specific cache block
Mage::app()->getCacheInstance()->getFrontend()->remove(strtoupper($id));
// no print, it's ok just warmup cache with filters processing
$block->toHtml();
}
Share
Improve this answer
Follow
answered Sep 13, 2016 at 15:52
Sylvain RayéSylvain Rayé
2,4561616 silver badges2323 bronze badges
Add a comment
|
|
My team and I are rapidly launching new stores and views on Magento Enterprise Edition but we're running into an issue with caching. To be clear, the caching part itself works great. We have several complex products that take about 17 seconds to build, but after its cached the pages loads in 300ms, which is awesome! Unfortunately, if we clear the cache under any serious load (high traffic) we seem to be experiencing a cache miss storm, where every page request is trying to populate the cache, causing our webhead to stall out with load averages above 50.
Do you have any suggestions for avoiding this? Are there documented best practices for pre-warming a cache for new code deployments or even just content and configuration changes?
This could be related, so I'll include it: After clicking the button to refresh the cache and before the refreshing process is complete most pages on the front end die with 500 error codes and seemingly random error messages. Any idea what might cause that?
|
Magento Cache Warming
|
0
Use something fast to create the hash crc32 is fast but might give you more collisions than md5 (although filename takes care of some).
<?php
function hash_buffer($content) {
$buffer_hash = crc32($content);
// You could add expire time so the check is not made every time.
// Or force it to happen always
header('Expires:');//.date('r',strtotime('+1 hour')));
// Add vary header so client knows to usee ETag
// Without overwriting existing vary headers
header('Vary: If-None-Match',false);
if ($_SERVER['HTTP_IF_NONE_MATCH'] == $buffer_hash) {
header('HTTP/1.1 304 Not Modified');
header("ETag: $buffer_hash");
return '';
}
header('Cache-Control: private, no-cache');
header("ETag: $buffer_hash");
return $content;
}
ob_start('hash_buffer');
?>
Try to get content faster to the buffer
To get content to be buffered generated faster you could use file caching. For example writing generated navigation/blogroll/newslist into a file and reading it from there if filemtime is within cache lifetime ( 10min - 1h etc.) otherwise write it down on file and handle as usual.
You need write locks to prevent collisions etc. see ZendFramework implementation on that https://github.com/zendframework/zf2/blob/master/library/Zend/Cache/Storage/Adapter/Filesystem.php#L1489
Remember
User rights might play a part on filecaching like with any cache you don't want someone else's shopping cart appear on you checkout page etc. Generally leaving authenticated users out of filecache is playing it safe.
When caching on files cache files must be safeguarded from public read and write access over the web and otherwise.
Share
Improve this answer
Follow
answered Aug 7, 2013 at 10:39
MTJMTJ
1,08911 gold badge1111 silver badges2323 bronze badges
Add a comment
|
|
I have been researching some strategies to optimize a web application I am working on particularly related to web browser caching and dynamic data. Since potentially the same dynamic content may be loaded multiple times in a session, I came up with the following method using PHP's output buffer and using a hash of the content as an ETag.
I realize that the only thing I really save with this method is the transfer of data back to the user since the PHP script still has to completely run, but I was curious if anyone has done something similar and if there are any thoughts or concerns I should be aware of or what other methods may be better.
Here is the code I am including at the top of each page:
<?php
function hash_buffer($content) {
$buffer_hash = crc32($content);
if ($_SERVER['HTTP_IF_NONE_MATCH'] == $buffer_hash) {
header('HTTP/1.1 304 Not Modified');
header("ETag: $buffer_hash");
return '';
}
header('Cache-Control: private, no-cache');
header("ETag: $buffer_hash");
return $content;
}
ob_start('hash_buffer');
?>
|
Browser Caching dynamic content using PHP output buffer and ETag
|
Memcache is volatile and it may flush data at any time, so this approach is very unreliable.
You would be best off using Push Task Queue. Use it via DeferredTask helper class. Here is an example.
|
To avoid the high latency (spikes) in GAE datastore writes, I want to implement a write-behind cache (using the Java low-level API). This means that data is written synchronously to the memcache, and then asynchronously to the datastore, so that the request can return quickly.
This, however, means that I need to somehow need to deal with Exceptions arising from datastore contentions (e.g. to initiate a retry) also asynchronously. More precisely, I need to be able to react to contention's occurring after the request has returned. How can I do that? Using the task queue for async write processing is not an option, because pushing to the queue is said to be only marginally faster than a datastore write.
If that is impossible, then what are good ways to implement a write-behind cache? Or how to deal with slow writes in a scenario where data loss is not an option.
|
How to handle GAE datastore contention asynchronously?
|
0
I don't think it makes sense to cache static content as these templates are precompiled and cached anyway in production - they are, in-fact, in memory.
Share
Improve this answer
Follow
answered Dec 12, 2012 at 15:41
Jiří PospíšilJiří Pospíšil
14.3k22 gold badges4242 silver badges5252 bronze badges
2
Even if other parts of the page are generated with ERB? I didn't mean to imply that the whole page was static.
– David Tuite
Dec 12, 2012 at 17:27
Well, when ERB template is compiled, it basically becomes a list of "_erbout.concat" method calls. The method takes a string as its argument or something that results in string - so your static parts are just static strings that get passed along, your dynamic parts are dynamic and result in string. So bottom line, the static parts are already there, no need to get them from some external storage.
– Jiří Pospíšil
Dec 13, 2012 at 8:26
Add a comment
|
|
When fragment caching non-dynamic html in Rails
<% cache [:long_list] do %>
<li><!-- Loads of html --></li>
<li><!-- Loads of html --></li>
<li><!-- Loads of html --></li>
<!-- Loads more li items... -->
<% end %>
In terms of the size of the content being cached, is there a point at which caching will result in a decrease in page rendering speed?
Ir more succinctly, is this likely to reduce performance?
<% cache :div do %>
<div id="empty-content"></div>
<% end %>
Assume the user of an in-memory cache such as memcached.
|
How small is too small to fragment cache?
|
0
Optimize your website loading time by compressing files into smaller size.
Add this to your .htaccess file
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript application/json
Share
Improve this answer
Follow
answered Dec 12, 2012 at 10:37
JorisWJorisW
12811 silver badge77 bronze badges
1
Unfortunately, this doesn't make a difference, at all.
– 30secondstosam
Dec 12, 2012 at 11:33
Add a comment
|
|
I'm currently trying to speed up the ajax requests made. Basically the site works by live filtering. So when a user clicks on a form element, the data will load accordingly. This all works fantastically well but it's not as quick as I want it to be.
My AJAX looks a bit like this (i've obviously omitted the variables):
$.ajax({
type: "GET",
url: 'URL NAME',
data: {
'Var1': Var1,
'Var2': Var2
},
cache:true, // Set cache to TRUE
success: function(data) {
$('.content').html(data);
},
complete: function () {
$("#loading_ajax").hide();
$('.content').fadeIn();
}
}).error(function (event, jqXHR, ajaxSettings, thrownError) {
$('.content').html("<h2>Could not retrieve data</h2>");
//alert('[event.status:' + event.status + '], [event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
});
On the other side where the data is getting requested, the first lines in the PHP are this:
$seconds = 86400;
header("Cache-Control: private, max-age=$seconds");
header("Expires: ".gmdate('r', time()+$seconds));
I then went into Firebug to check for caching and it didn't seem to work at all.
Firebug printed out the following:
The second screenshot there shows that the request had actually slowed down (I repeated it to see if the caching would improve it and it hasn't made a difference). Any ideas? Thanks.
|
JQuery AJAX Caching with PHP file
|
Depends on your platform. Most modern CPUs have hardware performance counters which could potentially be used to count cache-misses, but access to these may be awkward. Windows, for example, generally expects you to write a kernel-mode driver.
You might be better off getting some decent performance analysis software and running your code through that.
|
int sumarrayrows(int a[M][N])
{
int i, j, sum = 0;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
sum += a[i][j];
return sum;
}
I was wondering how to find the miss rate of any cache friendly code and does measure the size of a cache or a cache block if so how to find the size of it.
Update I figured out how to find the miss rate
Since this uses 4 bytes
there will be a 25% chance of a miss rate
a[0] = M
a[1] = H
a[2] = H
a[3] = H
|
How to find the miss rate in a cache friendly code?
|
0
I'm pretty sure that tornado caches the templates as well. Taken from their docs
Loader is a class that loads templates from a root directory and caches the compiled templates:
So if your calling loader it might be your issue.
Share
Improve this answer
Follow
answered Nov 19, 2012 at 0:40
enjoylifeenjoylife
3,82122 gold badges2525 silver badges3434 bronze badges
1
1
Fixed. I passed debug=True in the Application constructor as per the doc and it worked. Thanks for the help!
– luisdaniel
Nov 19, 2012 at 1:11
Add a comment
|
|
I'm starting to learn Tornado and going through the Intro to Tornado book.
While working through one of the examples, I had a missing quote in an HTML file and got the following error:
File "modules/book_html.generated.py", line 11
if book["subtitle] != "": # modules/book.html:3
SyntaxError: EOL while scanning string literal
This is what book.html looks like:
<div class="book">
<h3 class="book_title">{{ book["title"] }}</h3>
{% if book["subtitle"] != "" %}
<h4 class="book_subtitle">{{ book["subtitle"] }}</h4>
{% end %}
<img src="{{ book["image"] }}" class="book_image"/>
<div class="book_details">
<div class="book_date_released">Released: {{ book["date_released"]}}</div>
<div class="book_date_added">Added: {{ locale.format_date(book["date_added"], relative=False) }}</div>
<h5>Description:</h5>
<div class="book_body">{% raw book["description"] %}</div>
</div>
</div>
Added the missing quote, restarted the server (running on localhost) and still got the same error. Copy-pasted code exactly from book's github, still same error. Commented out the entire file, same thing. Replaced the entire code (all files, main.py, everything in templates folder, everything) with the code from github, same thing.
It looks like Chrome is caching the file or something, but I even changed the filename to book2.html, and the error came out with the changed file name:
File "modules/book2_html.generated.py", line 11
if book["subtitle] != "": # modules/book2.html:3
I tried clearing the cache, no luck. I went to Chrome's developer tools and checked the Disable cache checkbox, same. I also tried running the web app in Firefox and same thing.
Has anyone ever had a similar problem? Any help would be appreciated. Thanks!
|
Change in html file does not take effect when I restart tornado server
|
I ended up monkey patching something like this for now: https://gist.github.com/4062316
Not sure how safe it is yet, but seems to be working. Would be awesome to see something like this in the standard Rails.cache though.
|
The :race_condition_ttl option for Rails.cache.fetch seems REALLY close to what I want: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch
But it seems like it still blocks the first request that encounters an expired value (it's only subsequent requests after that which get the old value and return quickly while the cache is being updated).
I guess I'm surprised it doesn't serve the first expired request the same way and was wondering if there was a common pattern for this or if it had to be custom.
|
Why does the :race_condition_ttl option for Rails.cache.fetch still block the first request?
|
You can download it to the SDcard (or anywhere) and then play it back using the public void setDataSource (String path) method of MediaPlayer
mediaPlayer.setDataSource(Environment.getExtrnalStorageDirectory() + "/yoursoundfile.mp3");
you may have to tweak the path to get it correct.
http://developer.android.com/reference/android/media/MediaPlayer.html#setDataSource(java.lang.String)
|
How to cache into disk audio streamed into MediaPlayer? I'd like to use cached audio instead of downloading it each time. Unfortunately setDataSource even do not accepts InputStream, so I don't know solution.. My code:
mediaPlayer.setDataSource(context, Uri.parse(/* file url */));
mediaPlayer.prepare();
mediaPlayer.start();
|
How to cache into disk audio streamed into MediaPlayer?
|
Thanks for all the answers.
I realized that if I want to use the ChangeMonitor class I would have to extend it to monitor memory segments. The better solution in my case would be to alert the cache that a function result has changed. I have done this by adding a method 'Reset' to MyFunction class. Every time a parameter changes I just call the Reset function which will invalidate the cache.
|
I have various function classes that preform long calculation. Currently every access to the result of the functions means recalculating the functions. That's why I want to incorporate MemoryCache in my solution. But the problem is that I need a ChangeMonitor Class that monitors the function class for changes. I have seen examples that monitor a file. My question is: do I need to write a custom ChangeMonitor or am I missing a simple solution?
An example just to be clear:
class MyFunction
{
//I want to monitor changes to these parameters
private int param1;
private int param2;
//This result should be cached
public int GetResult()
{
return param1 * param2;
}
};
|
MemoryCache for Object
|
As long as the Web pages don't call LocalStorage.clear before they exit the data should be available in a SQLite database.
If my memory is correct is under 4.03 the path is something like /data/data//app_database/localstorage/file__0.localstorage
As the local storage data is saved in a SQLite table called ItemTable you can read this data using the SQLite APIs (when in the same context).
So you could pre-populate the table from your service by inserts into this table.
Sorry to not paste any code - I dont have it with me but this will work - I have done it
|
I'm using WebView in my application and I need to pre-cache some webpages for later use. Since I want the caching process be less obnoxious, it have to be unnoticeable. So it's better to be implemented in a Service.
I don't know how to achieve this because WebView can only exist in an activity. Is there any method to cache webpages to local storage, and let WebView load it later? Or how can I realize the features with another approach?
|
External cache for WebView to load?
|
0
Symfony2 supports ESI (Edge side include) Caching. You can Tag and cache only parts. Perhaps its what you mean.
Symfony2 ESI Caching
Share
Improve this answer
Follow
answered Oct 8, 2012 at 10:59
René HöhleRené Höhle
27k2222 gold badges7676 silver badges8787 bronze badges
2
What I mean is the control for the cache. So it is possible, in Zends world, to clear the cache related to certain items. If article 5 were edited, you're able to clean all cache related only to article 5.
– Daniel
Oct 8, 2012 at 11:02
Hmm ok but i think its not possible. Then you need something that know that the cache has changed. You can try it with varnish. symfony.com/doc/current/cookbook/cache/varnish.html
– René Höhle
Oct 8, 2012 at 12:01
Add a comment
|
|
I'm looking for something similar to Zend_Cache-Tags in Symfony2. The aim is caching different parts of the page and clean up the cache-parts, if the related data changes.
An Example: A shop-overview could tagged with 'article-2', 'article-5'...
How can I manage it in symfony2? Is it possible?
|
Cache-Tags in Symfony2/Twig?
|
0
Android alternative for NSURLCache is HttpResponseCache.
http://developer.android.com/reference/android/net/http/HttpResponseCache.html
This class supports HttpURLConnection and HttpsURLConnection; there is no platform-provided cache for DefaultHttpClient or AndroidHttpClient.
Share
Improve this answer
Follow
answered Nov 23, 2015 at 0:05
Animesh DasAnimesh Das
7955 bronze badges
Add a comment
|
|
I have custom caching engine in my iOS application.
AFURLCache* urlCache = [[[AFURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:@""] autorelease];
[NSURLCache setSharedURLCache:urlCache];
Now thinking of the Android version.
What would be the approach there? Is there a way to set in-house custom handling of HTTP requests?
|
NSURLCache alternative in Android
|
0
This is a known bug or rather the feature was not implemented properly. It didnt work for me in sencha 2.1 either.
Share
Improve this answer
Follow
answered Jul 31, 2013 at 8:45
Ram G AthreyaRam G Athreya
4,92266 gold badges2626 silver badges5757 bronze badges
Add a comment
|
|
In my SenchaTouch 2 app the first lines in app.js read:
Ext.Loader.setConfig( {enabled: true, disableCaching: false} );
Ext.data.Connection.disableCaching = false;
Ext.data.JsonP.disableCaching = false;
Ext.data.proxy.Server.prototype.noCache = false;
Ext.Ajax.disableCaching = false;
The app compiles to the production version without errors or warnings. It loads and runs from the server. When I try to run it offline in Chrome, those 404 errors occur
GET http://myServer/m/Override/...=1346682646496 /m/Override/slider/Slider.js?_dc=1346682646496:1
GET http://myServer/m/app.json?1346682646693 /m/:6
which indicate that the timestamp of the disableCache parameter is appended to the GET requests. Therefore the application does not load offline. It hangs at the "Application is being loaded..." screen. How can I enable caching and avoid this _dc parameter?
The SDK version is 2.0.1.1
-- update: Found workaround. Integrated Slider.js in app.js
|
Sencha Touch 2: Cannot disable the disableCache mechanism - app does not run offline
|
0
Distributed Caching, is feasible for query-able data sets.
But for this scenario there should either be native function or procedure that would give much faster results. If different scope are not possible like session or application then it would be much of iteration required on server side for fetching the data for each request.
Indexing on server side then of Database is never a good idea.
If still there are network issues. You could go ahead for Document Oriented or Column Oriented NoSQL DB. If feasible.
Share
Improve this answer
Follow
answered Aug 22, 2012 at 7:22
Anand SanghviAnand Sanghvi
9911 gold badge22 silver badges1010 bronze badges
Add a comment
|
|
My scenario is as follows. I have a data table with a million rows of tuples (say first name and last name), and a client that needs to retrieve a small subset of rows whose first name or last name begins with the query string. Caching this seems like a catch-22, because:
On the one hand, I can't store and retrieve the entire data set on every request (would overwhelm the network)
On the other hand, I can't just store each row individually, because then I'd have no way to run a query.
Storing ranges of values in the cache, with a local "index" or directory would work... except that, you'd have to essentially duplicate the data for each index, which defeats the purpose of even using a distributed cache.
What approach is advisable for this kind of thing? Is it possible to get the benefits of using a distributed cache, or is it simply not feasible for this kind of scenario?
|
Is it feasible to use a distributed cache for queryable data sets?
|
You can insert a service broker message from a trigger. Your application can listen on that particular message queue. That allows you do build arbitrary notification logic, including aggregation.
SqlDependency uses service broker internally, but with less flexibility.
|
i know about query notifications, but they're so limited because of lack of support for aggregation functions. so if i forget the SqlDependancy what other options do i have for OUTPUT caching in ASP.NET website? is there a way to call an outside code from inside of SQL Server?(2005 and above). like calling a webservice from a trigger?
it is important to say that my data is not changed so regularly which makes the polling technique so "not right for the job". the reason for that is because of me having a shopping website which needs the data to be fresh, so anytime a change has been made it has to be shown to the user immediately. that is why i'm looking for a similar technique to query notification but without its limitations.
|
caching with no notification and no polling, is there another way around it
|
0
The garbage collector won't recycle your bitmap if something is still referencing it. I would imagine that you have ImageViews hanging onto your bitmaps. ViewPager doesn't recycle Views so you'll need to clear out your ImageView when it's not being shown.
Share
Improve this answer
Follow
answered Aug 7, 2012 at 20:30
Christopher PerryChristopher Perry
39k4444 gold badges146146 silver badges187187 bronze badges
Add a comment
|
|
I have a ViewPager with ImageView as child views. The ImageView displays Bitmap loaded from network and/or cached to local cache implemented as LruCache based class (from Android support library). The problem is that when the images are removed from LruCache, the GC seems to not release or release too late the bitmap memory. I very often get the exception OutOfMemory while loading new bitmap from network/disk even if the old bitmaps are removed from LruCache and from the holding ImageViews of ViewPager (I removed views from ViewPager). I read that sometimes (?) you must call the Bitmap.recycle (prior to Android 3.0) but this does not work. It also does not work on ICS (I do not call Bitmap.recycle there).
How to solve this problem?
|
android Bitmap caching for ViewPager issue
|
0
I would investigate the answers posted here.
Is there a cross-browser onload event when clicking the back button?
I just changed this answer because some of the utilities I was referring to are pretty old and not maintained, which is not a useful answer.
Share
Improve this answer
Follow
edited May 23, 2017 at 10:34
CommunityBot
111 silver badge
answered Aug 6, 2012 at 23:47
fdsaasfdsaas
71444 silver badges1010 bronze badges
Add a comment
|
|
I have the following situation:
Page A: /something/new
Which posts back to: /something/create
Which redirects to Page B: /something/edit
So far it all works. Now, /something/edit is a page that lets you do a bunch of things through AJAX, so it starts up empty, and as you use it it gets "fuller", so to speak. If you reload at any time, you get everything back, rendered by the server.
However, if after being redirected, and making modifications to the page, you hit Back and then Forward again, the browser (Chrome at least) doesn't hit the server again (not even an Etag check that might result in a 304, nothing), it just loads Page B from cache, which shows up empty, and can be quite confusing...
When first rendering Page B, the server responds with the following headers:
Cache-Control:must-revalidate, private, max-age=0
Connection:Keep-Alive
Content-Length:18577
Content-Type:text/html; charset=utf-8
Date:Thu, 02 Aug 2012 20:19:59 GMT
Server:WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)
Set-Cookie: (redacted)
X-Miniprofiler-Ids:["ma2x1rjc0kgrijiug5dj","nnmovj2wz1lux85jwhd3"]
X-Request-Id:2dd3fa62799beadc1b39b8db1aa5f45f
X-Runtime:0.245014
X-Ua-Compatible:IE=Edge
I don't see an Etag, or anything similar that could be bothering. Also, if I'm interpreting "Cache-control" correctly (i'm not very experienced with it, though), it seems to be saying to not cache, ever...
Is there any way to avoid this behaviour, and have the browser hit the server again on Back/Forward?
Thanks!
Daniel
|
Rails 3: How to prevent the browser from loading a page from cache on back/forward navigation?
|
0
This is indeed an issue, and seems to be specific to Chrome. In my case I was only concerned about a stale page being displayed if it contained a form, and all my forms are submitted using the same AJAX form library that I wrote, so I added this code to run prior to doing the redirect (the redirect is done in JS using window.location = ...):
//If the user clicks the back button after submitting the form and being redirected,
//Google Chrome redisplays previous entries even if they have since been changed
//(its caching works differently from other browsers).
//This is a (non-foolproof) hack to try to prevent this.
if (window.chrome) {
//This re-requests the page headers for the current page,
//which causes Chrome to clear its cache of the page.
//Unfortunately there appears to be no other client-side way of preventing this caching issue in Chrome.
$.ajax({
url: window.location,
method: 'HEAD'
})
}
Of course it would be much cleaner to just set no-cache headers on the server-side, but I didn't want to do that for all pages, and I didn't want to bother detecting which pages contain forms (or manually setting the cache headers on those pages) just to prevent this issue in Chrome.
I hope there is a better solution, but I haven't found one yet...
Share
Improve this answer
Follow
answered May 27, 2015 at 21:04
Matt BrowneMatt Browne
12.3k44 gold badges6060 silver badges7676 bronze badges
Add a comment
|
|
When you press the back button in Google Chrome, it seems it caches the source code (as opposed to the DOM in FF, but that is just observation, not some thing I know for sure).
Some times I need to prevent such caching, for example when you are in a checkout process, redirects to paypal etc.
How do I do it?
|
prevent caching when pressing BACK buttons
|
"Private" is the default value for the cache.
|
After having this issue on our websites over secure SSL connections for Office file download with Cacheability setting. I am wondering what would be the correct setting to use.
If I completely remove this following line of code, what would be the default Cacheability for the page? I have read the following page so if i set nothing what would be the default?
Response.Cache.SetCacheability(HttpCacheability.Public)
If I can't use No-cache then shall I use private or public safely then setting nothing?
Thanks.
|
what is the default Cacheability of a page ? asp.net IE
|
According to Sergio's and Craig's answers in comments to my question I assume that easiest way "to cache" some data in MongoDB is to create separate collection for storing data. Or (if it's not an option, as in my case) to use built-in ASP.NET cache.
|
I have some client-server application. And as one of its part, I need to implement a paginal approach on client side. I am making data footprint from db (I'm using MongoDB with 10gen's driver) on server-side and then give part of the footprint on client's request.
I have a problem with storing the footprint. I can't store it on server as local variable, because it simply don't save any data after completing method. I figured out that the footprint data can be stored as a MongoDB cache. But I don't know how it works.
Googling didn't made any progress for me. So can anybody explain me how to implement this MongoDB caching in C#?
|
How to cache some temp data in MongoDB?
|
0
Try this blog post by Arthur Vickers on the EF Team: http://blog.oneunicorn.com/2012/04/21/code-first-building-blocks/
It specifically shows how to cache a compiled model.
Share
Improve this answer
Follow
answered Jun 12, 2012 at 14:07
Julie LermanJulie Lerman
4,61222 gold badges2323 silver badges2121 bronze badges
3
1
I've already tried that, unfortunately once you built the ModelBuilder and compiled the DbModel, the resulting DbCompiledModel cannot be serialized in order to be transported to the distributed cache system. It can only be used/cached on the same AppDomain it was created.
– Ionut
Jun 12, 2012 at 20:36
i've pointed Arthur this way. If it can be done, he'll know. In the other hand, what about (a hack), creating an EDMX from the model at run time. THat's XML. YOu can move that around. Not sure what you would do with it after moving it across the wire though. ;)
– Julie Lerman
Jun 13, 2012 at 13:06
@JulieLerman Could this DbCompiledModel be serialized to JSON saved as a file in the application directory and then be deserialized in Application_Start? I am already generating the views and saving them to XML files. Caching the DbCompiledModel might also help with my initial cold start for queries.
– Issa Fram
Jun 21, 2018 at 20:31
Add a comment
|
|
I work on a Entity Framework Code First project with a large dbContext (800+ entities).
The problem I have is that it takes up to 30 seconds to build and compile the metadata for the first time and I cannot afford having all farm servers delay the first request (WCF) in such a manner, even with the help of the AppFabric WarmUp module.
An option is to cache the compiled model on a distributed cache, so other servers in the farm could take the advantage of an already existing model, when instantiating the DbContext.
Some things I found out:
A DbCompiledModel instance cannot be serialized;
DbCompiledModel uses an implementation of 'ICachedMetadataWorkspace' to cache its metadata, called 'CodeFirstCachedMetadataWorkspace';
'CodeFirstCachedMetadataWorkspace' (or even 'ICachedMetadataWorkspace') could indeed be used to provide a serializable workspace (along with the help of a 'DbDatabaseMapping.ToMetadataWorkspace' method) which to be stored as xml on the distributed cache;
Unfortunately all mentioned types are defined as internal by EF Code First (except of course DbCompiledModel) and until now I couldn't find a suitable way to cache this out of the process.
Another thing I've tried was to have a custom ObjectContext (to use it in DbContext constructor) where to programmaticaly generate/load the csdl, ssdl and msl mappings (from the db schema), but the actual views (poco classes) still remain unmapped to the overall db context.
Any help is much appreciated.
Thanks.
|
How to cache DbCompiledModel (or only its metadata) in a distributed cache
|
0
Have a look at this tutorial about taking a Sencha Touch app offline - it's not Sencha Touch 2 but it might point you in the right direction
Share
Improve this answer
Follow
answered Jul 19, 2012 at 4:37
DeanDean
4,55477 gold badges3535 silver badges4545 bronze badges
Add a comment
|
|
Assuming that I have followed the Sencha Touch 2 Getting Started tutorial, and have a list populated by JsonP proxy data- how do I go about making cached data appear if the user is offline? Currently, the list is simply not displayed if there is no internet connection.
In the video tutorial, Ed briefly mentions that this can "easily be done" but did not provide a reference to where I might find this in the Sencha documentation.
Below is an example of my store object:
Ext.define('test.store.NewsListStore', {
extend : 'Ext.data.Store',
requires: ['test.model.NewsListModel', 'Ext.data.Request'],
config : {
model : 'test.model.NewsListModel',
storeId : 'news-list-store',
autoLoad: true,
proxy: {
type: 'jsonp',
url : 'http://example.com/jsonp',
config : {
noCache: false
}
},
grouper : {
groupFn : function(record) {
var unix_timestamp = parseInt(record.get("entry_date"));
var date = new Date( unix_timestamp*1000 );
return Ext.Date.format(date, 'F');
}
},
}
});
|
Sencha Touch 2 Offline Caching with JsonP Proxy
|
0
With anything to do with caching, the first thing to do is always to inspect the response headers (you can use browser dev tools for this).
My guess is the first request is returning a set-cookie header for the rails session, which is causing rack cache to treat the response as uncacheable, and for good reason. The subsequent request does not return set-cookie since there already is a session, and rack cache stores it. The third request hits the previously cached content.
Share
Improve this answer
Follow
answered Jul 20, 2013 at 21:51
Johnny CJohnny C
1,77711 gold badge1919 silver badges2828 bronze badges
Add a comment
|
|
Good afternoon,
I have got Memcached set up decently well in my Heroku app. However, there is some odd behaviour that makes me wonder whether or not I've got it set up correctly.
When I visit a page in my app (set up with caches_page), I get a miss, then miss/store, then fresh. I feel like the first hit should be miss/store...
This is what I mean. First visit:
2012-04-07T21:07:11+00:00 app[web.1]: Started GET "/help" for xx.xx.xx.xx at 2012-04-07 21:07:11 +0000
2012-04-07T21:07:11+00:00 app[web.1]: cache: [GET /help] miss
Second visit:
2012-04-07T21:07:16+00:00 app[web.1]: cache: [GET /help] miss, store
Third visit:
2012-04-07T21:07:19+00:00 app[web.1]: cache: [GET /help] fresh
I'm not sure if this is actually a problem, or if I should go about my merry way. Thanks!
|
Rails 3 / Heroku / Memcached - Miss / Miss,store / Fresh
|
0
It sounds like what you really need is a pipeline. Grep handles this use case well by allowing you to re-filter previously filtered results by accepting data on standard input.
For example:
# Search for "bar" in lines that have "foo."
grep foo * | grep bar
# Search for "baz" in lines that don't have "quux."
grep -v quux * | grep baz
Share
Improve this answer
Follow
answered Jun 10, 2012 at 14:16
Todd A. JacobsTodd A. Jacobs
82.8k1515 gold badges143143 silver badges203203 bronze badges
Add a comment
|
|
Is there such a thing as a cached grep? I'm thinking of something that caches the files for which grep was issued against so that it doesn't need to re-traverse the directory, or reload those files. Does something like this already exist?
|
Is there such a thing as a cached grep?
|
0
Using ASP.NET Ajax may help if there are some parts of the page that need to interact with the server frequently. However, in my experience, ASP.NET Ajax doesn't live up to the promise of Ajax in terms of low latency interactions because of the ViewState bloat that accompanies all ASP.NET pages of any reasonable complexity.
I've found Scott Mitchell's article on Persisting Page State to be a very good resource for ideas for getting away from massive ViewState in ASP.NET web forms. I've used his FileSystemPageStatePersister with good results on production systems, however, the approach is incompatible with ASP.NET Ajax, and may not scale well to a web farm.
Share
Improve this answer
Follow
answered May 23, 2012 at 20:53
saillesaille
9,11255 gold badges4646 silver badges5757 bronze badges
Add a comment
|
|
I have a ASP.NET user control... comprising of a bunch of business-workflow-defined radio buttons.
Depending on the intial set of options chosen:
1) More radio button options load as a part of a tree control
2) Depending on option chosen - in turn loads one of the 5 other ASP.NET usercontrols dynamically.
There are postbacks and page reloads in between these transitions.
What options for performance enhancement can be applied to this legacy code?
|
ASP.NET User control performance enhancement
|
0
The Fallback Header has to be on it's own line, like so:
NETWORK:
*
(new line after the colon).
Share
Improve this answer
Follow
answered May 14, 2012 at 15:27
codecandiescodecandies
27922 silver badges44 bronze badges
Add a comment
|
|
I am using a manifest file to cache my files. Between these files some are the index.html and some javascript libs.
After I tested my webpage , the files are successfully cached (i validated this with the web inspector), however when I open the page again the non-cached linked resources are not receiving response.
The link URL is ok because I can use the "copy link URL" option and paste the url in another browser tab and receive the response. But in my web page i am not receiving anything.
I tried using NETWORK: * with the same result.
Is this because the index.html shouldn't be cached if it has non-cached resources linked?
thanks in advance
|
HTML5 cache manifest index.html not loading linked files
|
0
When the back button is clicked, the page is returned to the original state stored in the browser history. Ajax tends to "break" the back button.
You could save some a flag in your session to say what content you loaded via ajax on the last view. When the page reloads you can check with the server what the previous page state was.
Alternatively change the fragment identifier when you do an ajax call using: window.location.hash( "new-url-hash" ). You'll still need to do an initial check with your javascript to see what the fragment id part of the url is. If you change any other part of the location property the page will reload.
HTML5 adds in the pushState() method to change the browser history. See the mozilla docs here. pushState() does not cause the page to reload.
Share
Improve this answer
Follow
edited Mar 1, 2012 at 4:28
answered Mar 1, 2012 at 4:23
SimonSimon
1,7551212 silver badges88 bronze badges
1
1
Thanks Simon, I've solved this problem by using SESSION. Anyway, thanks for your answer :D
– hanuman0503
Mar 15, 2012 at 14:57
Add a comment
|
|
I am using Jquery Ajax to load more content to my page when user scroll to the bottom of page, like this:
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$.ajax({
url: /* my url goes here */,
cache: true,
success: function(html){ /*append html to the bottom of page*/ }
});
}
});
The problem is that: when user press some link in my page then press the back button, the new content that loaded before disappear. How to keep the new content? Thanks in advance.
|
Caching page after ajax loading
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.