Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
As far as i know, L1 cache in a GPU behaves much like the cache in a CPU. So your comment that "This is as opposed to values in L1, which get evicted if they are not used often enough" doesn't make much sense to me
Data on L1 cache isn't evicted when it isn't used often enough. Usually it is evicted when a request is made for a memory region that wasn't previously in cache, and whose address resolves to one that is already in use. I don't know the exact caching algorithm employed by NVidia, but assuming a regular n-way associative, then each memory entry can only be cached in a small subset of the entire cache, based on it's address
I suppose this may also answer your question. With shared memory, you get full control as to what gets stored where, while with cache, everything is done automatically. Even though the compiler and the GPU can still be very clever in optimizing memory accesses, you can sometimes still find a better way, since you're the one who knows what input will be given, and what threads will do what (to a certain extent of course)
|
After Compute Capability 2.0 (Fermi) was released, I've wondered if there are any use cases left for shared memory. That is, when is it better to use shared memory than just let L1 perform its magic in the background?
Is shared memory simply there to let algorithms designed for CC < 2.0 run efficiently without modifications?
To collaborate via shared memory, threads in a block write to shared memory and synchronize with __syncthreads(). Why not simply write to global memory (through L1), and synchronize with __threadfence_block()? The latter option should be easier to implement since it doesn't have to relate to two different locations of values, and it should be faster because there is no explicit copying from global to shared memory. Since the data gets cached in L1, threads don't have to wait for data to actually make it all the way out to global memory.
With shared memory, one is guaranteed that a value that was put there remains there throughout the duration of the block. This is as opposed to values in L1, which get evicted if they are not used often enough. Are there any cases where it's better to cache such rarely used data in shared memory than to let the L1 manage them based on the usage pattern that the algorithm actually has?
|
CUDA: When to use shared memory and when to rely on L1 caching?
|
I had a read of the sw-toolbox docs and figured out how to do it. Just had to add this to my runtime caching:
// cache fonts hosted on google CDN
global.toolbox.router.get(/googleapis/, global.toolbox.fastest);
|
I've been playing with the Google Web Starter Kit (https://github.com/google/web-starter-kit) and have got a little progressive web app working but am stuck on one thing: caching static files from external CDNs.
e.g. I'm using MDL icons from https://fonts.googleapis.com/icon?family=Material+Icons I can't see a way to cache the request as the service worker only responds to URLs within my app domain.
Options I see:
Download the file and put it in a vendor folder. Advantages: easy to set up SW cache. Disadvantages: file won't stay up to date as new icons are added (though that won't really matter as my code will only use the icons available).
Use the NPM repo: https://www.npmjs.com/package/material-design-icons and use build step to copy CSS file from node_modules. Advantages: will allow auto-updating from NPM. Disadvantages: slightly more complex to set up.
Some fancy proxy method that would allow me to use the SW to cache an external URL. e.g. myapp.com/loadExternal?url=https://fonts.googleapis.com/icon?family=Material+Icons
I'm leaning towards option #2 right now but would be cool to know if option #3 is possible.
|
How can I cache external URLs using service worker?
|
Actual data store and cache should be synchronized using the third approach you've already described in your question.
As you add data to your definitive store (i.e. your SQL database), you need to enqueue this data to some service bus or message queue, and let some asynchronous service do the whole synchronization using some kind of background process.
You don't want get into this cases (when not using a service bus and asynchronous service):
Make your requests or processes slower because the user needs to wait until the data is both stored in your database and cache.
Have the risk of a fail during the caching process and not being able to have a retry policy (which is usually a built-in feature in a service bus or some message queues). Also, this failure can end up in a partial or complete cache corruption and you won't be able to automatically and easily schedule some task to fix this situation.
About using Redis key expiration, it's a good idea. Since Redis can expire keys using its built-in mechanism, you shouldn't implement key expiration from the whole background process. If a key exists is because it's still valid.
BTW, you won't be always on this case (if a key isn't expired it means that it shouldn't be overwritten). It might depend on your actual domain.
|
I cache some data in redis, and reading data from redis if it's exists, otherwise reading data from database and write the data in redis.
I find that there are several ways to update redis after updating database.For example:
set keys in redis to expired
update redis immediately after updating datebase.
put data in MQ and use consumer to update redis.
I'm a little confused and don't know how to choose.
Could you tell me the advantage and disadvantage of each way and it's better to tell me other ways to update redis or recommend some blog about this problem.
|
How to update redis after updating database?
|
memcached is a great option, and I see you mentioned this already as a possible option. Also Redis seems to be praised a lot as another option at this level.
On an application level, in terms of a more granular approach to cache on a file by file and/or module basis, local storage is always an option for common objects a user may request over and over again, even as simple as just dropping response objects into session so that can be reused vs making another http rest call and coding appropriately.
Now people go back and forth debating about varnish vs squid, and both seem to have their pros and cons, so I can't comment on which one is better but many people say Varnish with a tuned apache server is great for dynamic websites.
|
I'm thinking about the best way to create a cache layer in front or as first layer for GET requests to my RESTful API (written in Ruby).
Not every request can be cached, because even for some GET requests the API has to validate the requesting user / application. That means I need to configure which request is cacheable and how long each cached answer is valid. For a few cases I need a very short expiration time of e.g. 15s and below. And I should be able to let cache entries expire by the API application even if the expiration date is not reached yet.
I already thought about many possible solutions, my two best ideas:
first layer of the API (even before the routing), cache logic by myself (to have all configuration options in my hand), answers and expiration date stored to Memcached
a webserver proxy (high configurable), perhaps something like Squid but I never used a proxy for a case like this before and I'm absolutely not sure about it
I also thought about a cache solution like Varnish, I used Varnish for "usual" web applications and it's impressive but the configuration is kind of special. But I would use it if it's the fastest solution.
An other thought was to cache to the Solr Index, which I'm already using in the data layer to not query the database for most requests.
If someone has a hint or good sources to read about this topic, let me know.
|
Best way to cache RESTful API results of GET calls
|
I think I found my answer, and it deals with the page directory. The answer is yes, two mmapped regions of the same file will access the same underlying page cache data. However, each mapping needs to independently map each of the virtual pages to the physical pages -- meaning 2x as many entries in the page directory to access the same RAM.
Basically, each mmap() creates a new range in virtual memory. Every page of that range corresponds to a page of physical memory, and that mapping is stored in a hierarchical page directory -- with one entry per 4KB page. So every mmap() of a large region generates a huge number of entries in the page directory.
My guess is it doesn't actually define them all up front, which is why mmap() is instant to call even for a giant file. But over time it probably has to establish those entries as there are faults on the mmapped range, meaning over the course of time it gets filled out. This extra work to populate the page directory is probably why threads using different mmaps are slower than threads sharing the same mmap. And I bet the kernel needs to erase all those entries when unmapping the range -- which is why unmmap() is so slow.
(There's also the translation lookaside buffer, but that's per-CPU, and so small I don't think that matters much here.)
Anyway, it sounds like re-mapping the same region just adds extra overhead, for what seems to me like no gain.
|
To ask the question another way, can you confirm that when you mmap() a file that you do in fact access the exact physical pages that are already in the page cache?
I ask because I’m doing testing on a 192 core machine with 1TB of RAM, on a 400GB data file that is pre-cached into the page cache prior to the test (by just dropping the cache, then doing md5sum on the file).
Initially, I had all 192 threads each mmap the file separately, on the assumption that they would all get (basically) the same memory region back (or perhaps the same memory region but somehow mapped multiple times). Accordingly, I assumed two threads using two different mappings to the same file would both have direct access to the same pages. (Let’s ignore NUMA for this example, though obviously it’s significant at higher thread counts.)
However, in practice I found performance would get terrible at higher thread counts when each thread separately mmapped the file. When we removed that and instead just did a single mmap that was passed into the thread (such that all threads just directly access the same memory region), then performance improved dramatically.
That’s all great, but I’m trying to figure out why. If in fact mmapping a file just grants direct access to the existing page cache, then I would think that it shouldn’t matter how many times you map it — it should all go to the exact same place.
But given that there was such a performance cost, it seemed to me that in fact each mmap was being independently and redundantly populated (perhaps by copying from the page cache, or perhaps by reading again from disk).
Can you comment on why I was seeing such different performance between shared access to the same memory, versus mmapping the same file?
Thanks, I appreciate your help!
|
Does mmap directly access the page cache, or a copy of the page cache?
|
Any installed caching extensions will be listed in your phpinfo() file; They should be listed as one of the arguments in the "Configure Command" box (e.g. -enable-apc) and should have their own sections somewhere down the page.
Two of the most popular PHP caching modules are APC and Memcache.
|
I used to think caching was very hard to install so I've never done it... After reading about APC, it seems pretty easy to install. I always thought I would have to modify lots of PHP code inside my application to use it lol.
Anyways, I am wanting to install APC. I can use phpinfo() and notice it's not listed on the page, so it's not installed. Does this also show for the various other cache systems out there? I don't want to install APC if I have another caching system already installed since I'm not sure if it'll cause conflicts. Do hosts automatically install these for you?
What are the steps to check for to see if I have any sort of caching enabled?
|
How do I know if any PHP caching is enabled?
|
As long as you don't initialize the Memcached client yourself but you rely on Rails.cache common API, switching from Memcached to Redis is just a matter of installing redis-store and changing the configuration from
config.cache_store = :memcached_store
to
config.cache_store = :redis_store
More info about Rails.cache.
|
Is there a common api such that if I switch between Redis or Memcached I don't have to change my code, just a config setting?
|
Rails and caching, is it easy to switch between memcache and redis?
|
You want CSS and JS to be cached. It speeds up the loading of the web page when they come back. Adding a timestamp, your user's will be forced to download it time and time again.
If you want to make sure they always have a new version, than have your build system add a build number to the end of the file instead of a timestamp.
If you have issues with it just in dev, make sure to set up your browsers to not cache files or set headers on your dev pages to not cache.
|
This is how we prevent caching of JS and CSS files by browsers. This seems slightly hacky.. is there a better way?
<%
//JSP code
long ts = (new Date()).getTime(); //Used to prevent JS/CSS caching
%>
<link rel="stylesheet" type="text/css" media="screen" href="/css/management.css?<%=ts %>" />
<script type="text/javascript" src="/js/pm.init.js?<%=ts %>"></script>
<script type="text/javascript" src="/js/pm.util.func.js?<%=ts %>"></script>
Update: The reason we want to prevent caching is to ensure the newer version of the files are loaded when we do a new release.
|
Better way to prevent browser caching of JavaScript files
|
30
I just had this happen to me. Deleted the ".gradle" directory and then did a "Sync Project with Gradle Files". Once I did that, I was able to successfully build the project again.
Share
Improve this answer
Follow
answered Dec 11, 2014 at 18:26
JesseJesse
58044 silver badges77 bronze badges
1
remove .gradle and gradle --stop
– FrankyHollywood
Jul 4, 2022 at 13:03
Add a comment
|
|
I copied my project folder for wiping my hard drive and now, trying to import in Android Studio I get this error on buildgradle
Error:Could not add entry '2095793483774087535' to cache fileSnapshots.bin (/home/ivan/Forotek/.gradle/1.10/taskArtifacts/fileSnapshots.bin).
Corrupted IndexBlock 6198 found in cache '/home/ivan/Forotek/.gradle/1.10/taskArtifacts/fileSnapshots.bin'.
I tried importing in Windows, Mac & Linux, I get the same error always
|
Could not add entry to cache fileSnapshots.bin
|
If you are serving from IIS, We have manually disabled cache in our web.config file :
<system.webServer>
<httpProtocol>
<!--TODO: Remove this block for production (//TODO: Remove this block for production) -->
<customHeaders>
<!--DISABLE CACHE-->
<add name="Cache-Control" value="no-cache, no-store, must-revalidate" />
<add name="Pragma" value="no-cache" />
<add name="Expires" value="0" />
</customHeaders>
</httpProtocol>
</system.webServer>
|
I'm working on a TypeScript (0.9.1) project using Visual Studio 2012 with the latest Web Essentials as the IDE, and i debug using Chrome Developer tools.
Recently, and most probably after Chrome update (cur. Version 29.0.1547.66 m), typeScript files don't get updated after i edit them, and on the other hand the corresponding compiled js files are updated, but it seems that somehow the functionality still depends on the non-updated version of the sources.
Solutions tried and failed:
Rebuild the full solution.
Hard refreshing (Shift + F5) the local host site on chrome
Deleting Source map files and generate them again.
After some trials it looks like even a request to download the ts source files yields the non-updated version (http://localhost:1198/xxx.ts e.g)
It seems that the problem gets partially fixed after full restart (windows 8 if it matters), the source files are updated in chrome, but once i change it again, the same problem appears.
Another solution was using incognito, as it seems that it's a caching problem.
My question:
Is caching typeScript files that way is caused by a problem in the configurations of the project (even it was working before), or this is a bug in the new version of Chrome ?
|
Why Chrome doesn't update Typescript source files on change?
|
You need to modify the names of the external files you refer to. For e.g. add the build number at the end of each file, like style-1423.css and make the numbering a part of your build automation so that the files and the references are deployed with a unique name each time.
|
We are actively developing a website using .Net and MVC and our testers are having fits trying to get the latest stuff to test. Every time we modify the style sheet or external javascript files, testers need to do a hard refresh (ctrl+F5 in IE) in order to see the latest stuff.
Is it possible for me to force their browsers to get the latest version of these files instead of them relying on their cached versions? We're not doing any kind of special caching from IIS or anything.
Once this goes into production, it will be hard to tell clients that they need to hard refresh in order to see the latest changes.
Thanks!
|
How can I force a hard refresh (ctrl+F5)?
|
The proper way of doing it would be to use the invalidate method:
mycache.invalidate("somekey");
As specified in the API documentation:
void invalidate(Object key)
Discards any cached value for key key.
|
I am using import com.google.common.cache.Cache
I have initiated the cache this way:
private Cache<String,String> mycache =CacheBuilder.newBuilder()
.concurrencyLevel(4).expireAfterAccess(30, TimeUnit.MINUTES).build();
I am willing to remove entries manually in some scenarios before waiting for the expiration.
The only way I found to do this was this:
mycache.asMap().remove("somekey");
I am asking if that is the proper way of doing this? Am I going to have any problems with that?
|
Remove elements from Guava Cache
|
59
For cookies use delete_all_cookies() function
driver.delete_all_cookies()
for cache create profile
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.cache.disk.enable", False)
profile.set_preference("browser.cache.memory.enable", False)
profile.set_preference("browser.cache.offline.enable", False)
profile.set_preference("network.http.use-cache", False)
driver = webdriver.Firefox(profile)
Share
Improve this answer
Follow
edited May 29, 2023 at 16:01
Benjamin Loison
4,15444 gold badges1818 silver badges3535 bronze badges
answered Nov 3, 2017 at 10:05
Wojciech KuczerWojciech Kuczer
65166 silver badges66 bronze badges
1
2
Is there any way to clear cookies without creating a new instance of a web driver?
– Jenya Pu
Dec 7, 2021 at 23:47
Add a comment
|
|
I'm trying to clear the cache and cookies in my firefox browser but I can't get it to work. I have searched it up and i'm only getting solutions for java and C#. How do I clear the cache and cookies in Python?
selenium version: 3.6.0
platform: python
python version: 2.7.8
webdriver: geckodriver
browser platform: Firefox
|
python selenium clearing cache and cookies
|
This pushes the boundaries of my understanding of how Ruby uses memory, but I suspect that the most efficient implementation would be a doubly-linked list where every access moves the key to the front of the list, and every insert drops an item if the maximum size has been reached.
However, assuming Ruby's Hash class is already very efficient, I'd bet that the somewhat naive solution of simply adding age data to a Hash would be fairly good. Here's a quick toy example that does this:
class Cache
attr_accessor :max_size
def initialize(max_size = 4)
@data = {}
@max_size = max_size
end
def store(key, value)
@data.store key, [0, value]
age_keys
prune
end
def read(key)
if value = @data[key]
renew(key)
age_keys
end
value
end
private # -------------------------------
def renew(key)
@data[key][0] = 0
end
def delete_oldest
m = @data.values.map{ |v| v[0] }.max
@data.reject!{ |k,v| v[0] == m }
end
def age_keys
@data.each{ |k,v| @data[k][0] += 1 }
end
def prune
delete_oldest if @data.size > @max_size
end
end
There's probably a faster way of finding the oldest item, and this is not thoroughly tested, but I'd be curious to know how anyone thinks this compares to a more sophisticated design, linked list or otherwise.
|
What's the most efficient way to build a cache with arbitrary Ruby objects as keys that are expired based on a least recently used algorithm. It should use Ruby's normal hashing semantics (not equal?)
|
Efficient Ruby LRU cache
|
From the clientCache documentation
The value for the httpExpires attribute must be a fully-formatted date and time that follows the specification in RFC 1123. For example:
Fri, 01 Jan 2010 12:00:00 GMT
So, if you want to use the http expires headers for your static content, set it like this:
<staticContent>
<clientCache cacheControlMode="UseExpires" httpExpires="Sun, 1 Jan 2017 00:00:00 UTC" />
</staticContent>
Update (to above comments): This will most probably still not work in the built in VS server. I'm not sure if it supports expires headers at all. AFAIK this is an IIS setting.
|
I'm trying to get YSlow to give me an A on the "Add Expires header" section by setting the web.config file.
I've been looking around and this is what I put in based on what's out there:
<staticContent>
<clientCache httpExpires="15.00:00:00" cacheControlMode="UseExpires"/>
</staticContent>
</system.webServer>
This is what I'm seeing in Firebug:
Response Headers
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 28 Aug 2011 13:54:50 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: image/jpeg
Content-Length: 24255
Connection: Close
Request Headersview source
Host localhost:50715
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0
Accept image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Referer http://localhost:50715/MySite/SiteHome.html
Pragma no-cache
Cache-Control no-cache
However, when I look at it in Firefox, Yslow is still giving an F on this, even after a Crtl-F5
What am I missing?
Thanks.
|
http expire headers in asp.net with web.config
|
MongoDB will (at least seem) to use up a lot of available memory, but it actually leaves it up to the OS's VMM to tell it to release the memory (see Caching in the MongoDB docs.)
You should be able to release any and all memory by restarting MongoDB.
However, to some extent MongoDB isn't really "using" the memory.
For example from the MongoDB docs Checking Server Memory Usage ...
Depending on the platform you may see
the mapped files as memory in the
process, but this is not strictly
correct. Unix top may show way more
memory for mongod than is really
appropriate. The Operating System (the
virtual memory manager specifically,
depending on OS) manages the memory
where the "Memory Mapped Files"
reside. This number is usually shown
in a program like "free -lmt".
It is called "cached" memory.
MongoDB uses the LRU (Least Recently Used) cache algorithm to determine which "pages" to release, you will find some more information in these two questions ...
MongoDB limit memory
MongoDB index/RAM relationship
Mongod start with memory limit (You can't.)
|
Mongodb use the Memory Mapped File ,when I use a long time , I see the free memory has left less by command 'free -m' in ubuntu and the caching use a lot. Then kill the Mongodb the caching still cost a lot ? how can I release the caching ?
|
how to release the caching which is used by Mongodb?
|
The final thing that worked was:
header('Pragma: public');
header('Cache-Control: max-age=86400');
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
header('Content-Type: image/png');
Now the browser does not make requests for the image when loading a page with embeded one.
|
I have images (PNG) that are generated dynamically and will be embedded in websites and forums. When an image gets posted on a very busy page, there are a lot many connections to service for something that doesn't change often. I want to tell the browser for how long to cache it.
So what headers do I need? Currently, I have:
Cache-Control: max-age=86400
Content-Type: image/png
It seems that the browser is not caching the image (it is about 20-30kb). What else would be necessary?
Edit:
This is an example image, I already have an URL with .png extension:
https://images.carspending.com/sigimg/5734/user/honda-accord-2-4i-executive-tourer_medium.png
|
Headers for PNG image output to make sure it gets cached at browser?
|
Firefox supports this feature, now:
Firefox 32.0.3
To open the developer tools in Firefox, press F12 or Right click and select Inspect Element (Q).
|
I know that I can turn off the cache in Firefox going to about:config and setting network.http.use-cache and browser.cache.offline.enable to false.
But this is annoying when I want to turn off the cache temporary. I really like the feature of turning off cache only when dev tools are opened.
Is there any solution for Firefox?
I would prefer not to install add-ons if possible.
|
How can I turn off cache in Firefox only when developer tools are opened?
|
Following the Yahoo! Best Practices for Speeding Up Your Web Site,
you should Add an Expires or a Cache-Control Header and Configure ETags.
How you actually go about configuring the server to do this depends on far more information than you have provided in the question.
|
I tested my site with Chrome and got the following recommendation:
The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:
style.css
jquery.marquee.js
jquery.marquee.css
logo.png
How do I set the cache expiration for these files?
|
Set cache expiration?
|
Caching adheres to UTC time to offer uniform time calculations, so you specify a point in time at which the cached entry should expire, in UTC, and the cache will calculate the appropriate difference from now and expire it as expected.
Your code will not work as expected since your absolute expiration will be before your cache item is entered once cacheExpiryInSeconds seconds pass, resulting in immediate eviction. You cannot share a CacheItemPolicy instance when AbsoluteExpiration is set in the near future, annoying I know. :)
|
I'm confused about the AbsoluteExpiration property on CacheItemPolicy.
The MSDN documentation for it says "The period of time that must pass before a cache entry is evicted." It uses a System.DateTimeOffset to define the "period of time".
But if you look at DateTimeOffset's MSDN documentation, it says that it "represents a point in time ... relative to Coordinated Universal Time (UTC)." Reference also this StackOverflow thread.
Do you see the problem? AbsoluteExpiration expects a "period in time" (like 5 seconds or 2 hours), but it requires an object that represents a "point in time" (like Dec 21, 2012, 06:14:00 EST).
In the code below, I define a single policy for all items. I want every item to expire cacheExpiryInSeconds seconds after they are added. Can someone verify that I'm doing this the correct way?
public class MyCache : IRoutingInfoCache
{
MemoryCache _routingInfoCache;
CacheItemPolicy _cachePolicy;
public MyCache(int cacheExpiryInSeconds)
{
_routingInfoCache = new MemoryCache("myCache");
_cachePolicy = new CacheItemPolicy() {
AbsoluteExpiration =
new DateTimeOffset(
DateTime.UtcNow.AddSeconds(cacheExpiryInSeconds))
};
}
public void Put(string key, object cacheItem)
{
// based on how I constructed _cachePolicy, will this item expire
// in cacheExpiryInSeconds seconds?
_routingInfoCache.Add(new CacheItem(key, cacheItem), _cachePolicy);
}
}
|
Expiring a cached item via CacheItemPolicy in .NET MemoryCache
|
You want to use the "snapshot listener" API to listen to your query:
https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection
Here's some JavaScript as an example:
db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(querySnapshot) {
var cities = [];
querySnapshot.forEach(function(doc) {
cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));
});
The first time you attach this listener Firestore will access the network to download all of the results to your query and provide you with a query snapshot, as you'd expect.
If you attach the same listener a second time and you're using offline persistence, the listener will be fired immediately with the results from the cache. Here's how you can detect if your result is from cache or local:
db.collection("cities").where("state", "==", "CA")
.onSnapshot({ includeQueryMetadataChanges: true }, function(snapshot) {
snapshot.docChanges.forEach(function(change) {
if (change.type === "added") {
console.log("New city: ", change.doc.data());
}
var source = snapshot.metadata.fromCache ? "local cache" : "server";
console.log("Data came from " + source);
});
});
After you get the cached result, Firestore will check with the server to see if there are any changes to your query result. If yes you will get another snapshot with the changes.
If you want to be notified of changes that only involve metadata (for example if no documents change but snapshot.metadata.fromCache changes) you can use QueryListenOptions when issuing your query:
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QueryListenOptions
|
I am starting with Firestore. I've read docs and tutorials about the offline data persistence but I have not really clear if Firestore downloads data again even if the content hasn't been modified.
For example, if I have a query where the results will be updated once a week and I don't need that the app download the content again until the changes were made, what is the best way in terms of efficiency to write the code?
Thanks!
|
Firestore - Using cache until online content updates
|
Delete the contents of your public/assets/ directory. That's where precompiled files go, and they're served if they exist, rather than the request falling through to Sprockets. You can safely just nuke the whole directory, and things should work again.
|
I've been developing a site in rails, everything going relatively smooth. Suddenly my changes to the views and assets no longer show up. I change a stylesheet or some html and reload my browser at http://0.0.0.0:3000 and nothing changes. So I restart WEBrick and still nothing's changed. This is even the case if I change an image entirely.
The only way to get the new changes is to precompile the assets:
C:\Users\me\website>rake assets:precompile
C:/Ruby193/bin/ruby.exe C:/Ruby193/bin/rake assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets
Why is it showing production as the RAILS_ENV? Maybe my development environment somehow turned into the production environment? But even then I shouldn't need to precompile assets to get changes reflected. Anyway Rails.env.development? returns true and Rails.env.production? returns false in controllers and erb files.
I've tried deleting my /tmp directory to no avail.
I had to add the following line to config/application.rb in order to get Heroku to work with compass:
config.assets.initialize_on_precompile = false
However, removing that line didn't help my issue anyway.
|
Rails dev environment not updating html/css/assets even after restarting server
|
Picasso doesn't have a disk cache. It delegates to whatever HTTP client you are using for that functionality (relying on HTTP cache semantics for cache control). Because of this, the behavior you seek comes for free.
The underlying HTTP client will only download an image over the network if one does not exist in its local cache (and that image isn't expired).
That said, you can create custom cache implementation for java.net.HttpUrlConnection (via ResponseCache or OkHttp (via ResponseCache or OkResponseCache) which stores files in the format you desire. I would strongly advise against this, however.
Let Picasso and the HTTP client do the work for you!
You can call setIndicatorsEnabled(true) on the Picasso instance to see an indicator from where images are being loaded. It looks like this:
If you never see a blue indicator, it's likely that your remote images do not include proper cache headers to enable caching to disk.
|
In Volley library, the NetworkImageView class requires an ImageLoader that handles all the image requests by searching for them inside an ImageCache implementation, the user is free to choose how the cache should work, the location and the name of the images.
I'm switching from Volley to Retrofit, and for the images I decided to try Picasso.
With the former library, I had a String parameter in each of my items containing the image URL, then I used myNetworkImageView.setImageUrl(item.getURL()) and it was able to determine if image was cached on disk. If the image existed in cache folder, the image was loaded, otherwise it was downloaded and loaded.
I would like to be able to do the same with Picasso, is it possible with Picasso APIs or should I code such feature by myself?
I was thinking to download the image to a folder (the cache folder), and use Picasso.with(mContext).load(File downloadedimage) on completion. Is this the proper way or are there any best practices?
|
Using Picasso with custom disk cache
|
I came across behavior that I thought was some kind of caching, but it turned out to be database transactions fooling me.
I had the problem where in another process, items were get added to the database, and I wanted to monitor progress of the other process, so I opened up a django shell and issued the following:
>>> MyData.objects.count()
74674
>>> MyData.objects.count()
74674
The value wasn't changing, even though it actually was in the database. I realized that at least with the way I had MySQL & django setup that I was in a transaction and would only see a "snapshot" of the database at the time I opened the transaction.
Since with views in django, I had autocommit behavior defined, this was fine for each view to only see a snapshot, as the next time a view was called it would be in a different transaction. But for a piece of code that was not automatically committing, it would not see any changes in the db except those that were made in this transaction.
Just thought I would toss this answer in for anyone who may come upon this situation.
To solve, commit your transaction, which can be manually done like so:
>> from django.db import transaction
>> transaction.enter_transaction_management()
>> transaction.commit() # Whenever you want to see new data
|
In my Django application, I repeatedly run the same query on my database (e.g. every 10 seconds).
I then create an MD5 sum over the queryset I receive and compare that to the MD5 sum I created in the previous run. If both are equal, the data has not changed and the web page does not need updating.
While I do this, the data in the DB might change.
However, the query returns the same queryset, apparently due to query caching.
How can I disable the query cache and explicitely execute the query on the DB ?
|
How to disable Django query cache?
|
On the model that you want to update you can do something like this:
class Video < ActiveRecord::Base
has_and_belongs_to_many :categories,
after_add: :touch_updated_at,
after_remove: :touch_updated_at
def touch_updated_at(category)
self.touch if persisted?
end
end
Now, whenever a category is added to or removed from a video, the video's updated_at timestamp will get updated. You can do the same thing on the category class if you want categories to update when videos are added to or removed from them.
|
If you have 2 models, Video and Category and they have a "has_and_belongs_to_many" relation with each other, how do you perform a touch to invalidate the cache when one of them changes?
You can't put "touch" on them like you can with a one-to-many relation. Now when i change a category name, the videos that belong to that category don't know about the change until i invalidate the cache. My View Templates show the name of the Category for each Video.
|
How to touch a HABTM relation
|
There are some good sources but you want to cache you processing server side and client-side.
Adding HTTP headers should help in the client side caching
here are some Response headers to get started on..
You can spend hours tweaking them until you get the desired performance
//Adds document content type
context.Response.ContentType = currentDocument.MimeType;
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
context.Response.Cache.SetMaxAge(new TimeSpan(0,10,0));
context.Response.AddHeader("Last-Modified", currentDocument.LastUpdated.ToLongDateString());
// Send back the file content
context.Response.BinaryWrite(currentDocument.Document);
As for server side caching that is a different monster... and there are plenty of caching resources out there...
|
How can I use output caching with a .ashx handler? In this case I'm doing some heavy image processing and would like the handler to be cached for a minute or so.
Also, does anyone have any recommendations on how to prevent dogpiling?
|
How to use output caching on .ashx handler
|
Browsers take care of this for you automatically, actually. You have to go out of your way to get them to NOT cache css, js, html and images.
I'm not that familiar with ASP MVC, but I think they type of caching you're thinking of is opcode caching for your created dynamic output server-side?
|
I would like to have images, css, and javascript cached client-side on their browser when they load up a web page. There are so many different types of caching I am confused as to which ones to use with asp.net mvc.
Would it also be possible to have their browsers check for new or modified versions of these files?
Thanks!
|
how to cache css, images and js?
|
If you're using RewriteRule, just use R instead of R=301. For other purposes, you'll have to clear your browser cache whenever you change a redirect. (If you don't know how to clear your browser cache, googling for a how-to should provide a quick and easy answer - or feel free to comment and I'll help you out.)
Simply put, try to avoid 301s wherever possible until you've got your redirects working normally. If you can't avoid them, get ready to clear your browser cache regularly.
|
I'm trying to debug an .htaccess file. FireFox keeps caching redirects and I can't get around them. Normally I would hit Ctrl + F5, but because it has already redirected me to another page, that just refreshes the page I was sent to and not the url I typed in. Is there a way to force a refresh of a url?
Here's an example:
Redirect example.com/hi to example.com/hello, test in FireFox and it works
Remove this line from .htaccess
Type example.com/hi in FireFox, it still redirects to example.com/hello
Type example.com/hi in Chrome, it does not redirect
This is why I think it's a browser caching issue, not server caching.
Edit: This seems to be FireFox specific, a quick solution is to use Chrome instead. The cache expired after an hour, which is way too long when trying to debug.
|
Apache - how to disable browser caching while debugging htaccess
|
Turns out it was a Web API thing. I'd overlooked the fact that the response header clearly stated that caching was disabled.
Response as viewed in the Network tab of Google Chrome:
Upon further investigation (and as seen in the image above), caching is disabled in Web API controllers. Even the [OutputCache] attribute, which is used in regular MVC controllers, isn't supported.
Luckily I found this blog:
http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
which lead me to these two solutions:
ASP.NET Web API CacheOutput
CacheCow
I decided to go with CacheOutput as it lets me use attributes like:
[CacheOutputUntilToday] which supports server & client side caching.
Or if I wanted to just use client-side caching I can use something like:
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]
Which seemed a little easier at first glance that CacheCow's approach. And easier to refactor out later if need be.
Now additional requests give me a 200 (from cache):
With a refresh giving me a 304 Not Modified:
Problem solved! Hope this helps someone else.
|
I have a Web API written in ASP.NET that I'm consuming via AngularJS $http.
I have enabled caching in my AngularJS factory as follows but every request still returns a response of 200, never 200 (from cache) or 304 (and by every request I mean making the same web api request numerous times on the same page, revisiting a page I've already visited that contains a Web API request, refreshing said page etc).
angular.module('mapModule')
.factory('GoogleMapService', ['$http', function ($http) {
var googleMapService = {
getTags: function () {
// $http returns a promise, which has a 'then' function, which also returns a promise
return $http({ cache: true, dataType: 'json', url: '/api/map/GetTags', method: 'GET', data: '' })
.then(function (response) {
return response.data;
});
};
return googleMapService;
}]);
Am I missing something from the AngularJS side of things? Or is this a Web API problem. Or both?
|
How to cache .NET Web API requests (& use w/ AngularJS $http)
|
25
If you have redis you can use sth like Rails.cache.redis.keys
Share
Improve this answer
Follow
answered Oct 7, 2020 at 10:13
sekmosekmo
1,6192222 silver badges2828 bronze badges
Add a comment
|
|
I want to maintain an user online/offline list with Rails.cache(memory_store).
Basically if a request /user/heartbeat?name=John reached Rails server, it will simply:
def update_status
name = params.require(:name)
Rails.cache.write(name, Time.now.utc.iso8601, expires_in: 6.seconds)
end
But how could I get all the data stored in Rails.cache similarly as following?
def get_status
# wrong codes, as Rails.cache.read doesn't have :all option.
ary = Rails.cache.read(:all)
# deal with array ...
end
I googled for a while, it seems Rails.cache doesn't provide the method to get all the data directly. Or there is better way to store the data?
I'm using Rails 5.0.2.
Thanks for your time!
|
rails: how to get all key-values from Rails.cache
|
In Firefox you can install a plugin called Web Developer Toolbar which has a appcache clear command
I think there is no way to do it programmatically but you could give a hint to the browser using something like
<script type="text/javascript" src='js/my.js?x=<?php echo rand(0,100) ?>'></script>
|
I'm working on JavaScript for a site, developing with Firefox, and when I refresh the page, I don't see my changes. The JavaScript file is in an external file. I reloaded and refreshed the page several times, but the old JavaScript file was still cached. Finally, I loaded the JavaScript page in the browser directly, saw the old script, hit 'reload', and saw my changes.
How can I clear cached external JavaScript files? I'll need to know this also when I tell the client that the changes are made, so that they aren't seeing the old cached functionality.
|
Clear cached JavaScript includes in Firefox
|
The Main difference is that the Add() method tries to insert a cache without overwriting an existing cache entry with the same key.
While the Set() method will overwrite an existing cache entry having the same key. [ However If the key for an item does not exist, insertion will be done as a new cache entry ].
Above was the difference in terms of their functionality.
Syntactical Difference:
One significant syntactical difference is that the Add() method returns a Boolean which is true if insertion succeeded, or false if there is already an entry in the cache that has the same key as item.
The Set() method has a void return type.
One last point that internal implementation of Add() method actually calls its corresponding version of AddOrGetExisting() method.
public virtual bool Add(CacheItem item, CacheItemPolicy policy)
{
return this.AddOrGetExisting(item, policy) == null;
}
|
From the doc
Add(CacheItem, CacheItemPolicy) : When overridden in a derived class, tries to insert a cache entry into the cache as a CacheItem instance, and adds details about how the entry should be evicted. [1]
-
Set(CacheItem, CacheItemPolicy) : When overridden in a derived class, inserts the cache entry into the cache as a CacheItem instance, specifying information about how the entry will be evicted. [2]
I see little difference in the wording (tries to) and signature (set is a sub, add returns a boolean), but I'm not sure which one I should use and if there is really something different between both.
|
What is the difference between "Set" and "Add" for ObjectCache?
|
After some more searching, I found JGroup's ReplicatedHashMap. It has not been thoroughly tested but it seems like an excellent start. It fills all my requirements without giving me too much features I don't need. It's also quite flexible. I'm still searching for the "perfect" answer though :)
Thanks for your answers.
|
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 10 years ago.
Improve this question
I am searching for a java framework that would allow me to share a cache between multiple JVMs.
What I would need is something like Hazelcast but without the "distributed" part. I want to be able to add an item in the cache and have it automatically synced to the other "group member" cache. If possible, I'd like the cache to be sync'd via a reliable multicast (or something similar).
I've looked at Shoal but sadly the "Distributed State Cache" seems like an insufficient implementation for my needs.
I've looked at JBoss Cache but it seems a little overkill for what I need to do.
I've looked at JGroups, which seems to be the most promising tool for what I need to do. Does anyone have experiences with JGroups ? Preferably if it was used as a shared cache ?
Any other suggestions ?
Thanks !
EDIT : We're starting tests to help us decide between Hazelcast and Infinispan, I'll accept an answer soon.
EDIT : Due to a sudden requirements changes, we don't need a distributed map anymore. We'll be using JGroups for a low level signaling framework. Thanks everyone for you help.
|
Cluster Shared Cache [closed]
|
Here's a way to do it that doesn't require IPackageDataObserver.aidl:
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
You will need to have this in your manifest:
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
This requests that Android clear enough cache files so that there is 8GB free. If you set this number high enough you should achieve what you want (that Android will delete all of the files in the cache).
The way this works is that Android keeps an LRU (Least Recently Used) list of all the files in all application's cache directories. When you call freeStorage() it checks to see if the amount of storage (in this case 8GB) is available for cache files. If not, it starts to delete files from application's cache directories by deleting the oldest files first. It continues to delete files until either there are not longer any files to delete, or it has freed up the amount of storage you requested (in this case 8GB).
|
In an Android app I am making, I want to be able to programmatically clear the cache of all of the apps on the device. This has been asked many times before:
Clearing app cache programmatically?
Reflecting methods to clear Android app cache
Clear another applications cache
and everyone says it's not possible without root.
However, this is clearly not the case. If you look at the apps App Cache Cleaner, History Eraser, 1Tap Cleaner, Easy History Cleaner, and countless other similar apps in the Google Play (all of which don't require root) you will realize they can all do this. Therefore, it IS possible to do, but I just cannot find any public examples how to do this.
Does anyone know what all of those apps are doing?
Thanks
|
Android: Clear Cache of All Apps?
|
The basic idea, when executing a PHP script is in two steps :
First: the PHP code, written in plain-text, is compiled to opcodes
Then: those opcodes are executed.
When you have one PHP script, as long as it is not modified, the opcodes will always be the same ; so, doing the compilation phase each time that script is to be executed is kind of a waste of CPU-time.
To prevent that redundant-compilation, there are some opcode caching mechanism that you can use.
Once the PHP script has been compiled to opcodes, those will be kept in RAM -- and directly used from memory the next time the script is to be executed ; preventing the compilation from being done again and again.
The opcode cache which is used the most is **APC - Alternative PHP Cache** :
See on PECL to download the APC extension
And here's its manual
Once APC has been installed and configured properly, there is nothing you have to modify in your PHP code : APC will cache the opcodes, and that is all -- the process is totally invisible for your application.
|
I searched on the Web and came to know that PHP code can be compiled to have performance boost.
But how to do it?
Can I compile both procedural and object oriented PHP code?
|
What is a bytecode cache and how can I use one in PHP?
|
The imports are cached in $DENO_DIR
From the docs:
Deno caches remote imports in a special directory specified by the
$DENO_DIR environmental variable. It defaults to the system's cache
directory if $DENO_DIR is not specified. The next time you run the
program, no downloads will be made. If the program hasn't changed, it
won't be recompiled either. The default directory is:
On Linux/Redox: $XDG_CACHE_HOME/deno or $HOME/.cache/deno
On Windows: %LOCALAPPDATA%/deno (%LOCALAPPDATA% = FOLDERID_LocalAppData)
On macOS: $HOME/Library/Caches/deno If something fails, it falls back to
$HOME/.deno
Relying on external servers is convenient for development but brittle
in production. Production software should always bundle its
dependencies. In Deno this is done by checking the $DENO_DIR into your
source control system, and specifying that path as the $DENO_DIR
environmental variable at runtime.
You can see the information by running: deno info
what is the deno command to install all the dependencies mentioned in
dep.ts file
To install just import $DENO_DIR0 in one of your files and run:
$DENO_DIR1
|
I am new to deno and currently exploring for a minimum viable project in deno. I want to like npm which downloads the npm packages inside the folder node_modules, similarly I want to see the deno packages in a directory. In my current project I do not see any downloaded packages. Please suggest me where to look for deno packages. If I write dep.ts file to mention all the deno packages, can I use the same deno packages for some other projects. My question is bit similar to what Maven or Gradle in java handles. It means I want to know whether deno maintains a single folder in OS so that all the packages are downloaded and used in many projects. I want to check the directory containing the deno packages in windows 10.
|
Where can I see deno downloaded packages?
|
I've seen this before on App Engine, even when using cache-busting query parameters like /stylesheets/default.css?{{ App.Version }}.
Here's my (unconfirmed) theory:
You push a new version by deploying or changing a new version to default.
While this update is being propagated to all GAE instances running your app...
...someone hits your site.
The request for static resource default.css{{ App.Version }} is sent to Google's CDN, which doesn't yet have it.
Google's CDN asks GAE for the resource before propagation from step #2 is done for all instances.
If you're unlucky, GAE serves up the resource from an instance running the old version...
...which now gets cached in Google's CDN as the authoritative "new" version.
When this (if this is what happens) happens, I can confirm that no amount of cache-busting browser work will help. The Google CDN servers are holding the wrong version.
To fix: The only way I've found to fix this is to deploy another version. You don't run the risk of this happening again (if you haven't made any CSS changes since the race condition), because even if the race condition occurs, presumably your first update is done by the time you deploy your second one, so all instances will be serving the correct version no matter what.
|
I pushed a new version of my website, but now the CSS and static images are not deploying properly.
Here is the messed up page: http://www.gaiagps.com
Appengine shows the latest version as being correct though: http://1.latest.gaiagps.appspot.com/
Any help?
|
CSS File Not Updating on Deploy (Google AppEngine)
|
Well, all of today's modern operating systems use something called virtual memory. Every address generated by CPU is virtual. There are page tables that map such virtual addresses to physical addressed. And a TLB is just a cache of page table entries.
On the other hand L1, L2, L3 caches cache main memory contents.
A TLB miss occurs when the mapping of virtual memory address => physical memory address for a CPU requested virtual address is not in TLB. Then that entry must be fetched from page table into the TLB.
A cache miss occurs when the CPU requires something that is not in the cache. The data is then looked for in the primary memory (RAM). If it is not there, data must be fetched from secondary memory (hard disk).
|
Could someone please explain the difference between a TLB (Translation lookaside buffer) miss and a cache miss?
I believe I found out TLB refers to some sort of virtual memory address but I wasn't overly clear what this actually meant?
I understand cache misses result when a block of memory (the size of a cache line) is loaded into the (L3?) cache and if a required address is not held within the current cache lines- this is a cache miss.
|
TLB misses vs cache misses?
|
Serializing is quite safe and commonly used. There is an alternative however, and that is to cache to memory. Check out memcached and APC, they're both free and highly performant. This article on different caching techniques in PHP might also be of interest.
|
In ASPNET, I grew to love the Application and Cache stores. They're awesome. For the uninitiated, you can just throw your data-logic objects into them, and hey-presto, you only need query the database once for a bit of data.
By far one of the best ASPNET features, IMO.
I've since ditched Windows for Linux, and therefore PHP, Python and Ruby for webdev. I use PHP most because I dev several open source projects, all using PHP.
Needless to say, I've explored what PHP has to offer in terms of caching data-objects. So far I've played with:
Serializing to file (a pretty slow/expensive process)
Writing the data to file as JSON/XML/plaintext/etc (even slower for read ops)
Writing the data to file as pure PHP (the fastest read, but quite a convoluted write op)
I should stress now that I'm looking for a solution that doesn't rely on a third party app (eg memcached) as the apps are installed in all sorts of scenarios, most of which don't have install rights (eg: a cheap shared hosting account).
So back to what I'm doing now, is persisting to file secure? Rule 1 in production server security has always been disable file-writing, but I really don't see any way PHP could cache if it couldn't write. Are there any tips and/or tricks to boost the security?
Is there another persist-to-file method that I'm forgetting?
Are there any better methods of caching in "limited" environments?
|
Methods for caching PHP objects to file?
|
I think an easy way is to save the previous value in a transient variable that JPA will not persist.
So just introduce a variable previousSurname and save the actual value before you overwrite it in the setter.
If you want to save multiple properties it would be easy if your class MyClass is Serializable.
If so add a post load listener
public class MyClass implements Serializable {
@Transient
private transient MyClass savedState;
@PostLoad
private void saveState(){
this.savedState = SerializationUtils.clone(this); // from apache commons-lang
}
}
But be aware that the savedState is a detached instance.
You can then access the previous state in your EntityListener.
You can also move the PostLoad listener to the EntityListener class. But then you need access to the savedState field. I recommend to make it either package scoped or use a package scoped accessor and put MyClass and MyListener in the same package,
Serializable.0
|
Let's assume I have this class :
@EntityListeners({MyListener.class})
class MyClass {
String name;
String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return name;
}
public void setSurname(String name) {
this.name = name;
}
public void save() {
JPA.em().persist(this);
return this;
}
public void update() {
JPA.em().merge(this);
}
public static MyClass findById(Long id) {
return JPA.em().find(MyClass.class, id);
}
}
Now in my MyListener class I'm trying to figure out the previous value MyClass instance versus the new value that is about to get saved(updated) to database. I do this with preupdate metdhod :
@PreUpdate
public void preUpdate(Object entity) {
...some logic here...unable to get the old object value in here
}
So assuming I have a MyClass objects instance with name and surname :
MyClass mycls = new MyClass();
mycls.setName("Bob");
mycls.setSurname("Dylan");
mycls.save();
This wasn't picked up by listener which is ok because I'm listening only to updates.
Now if I were to update this instance like so :
MyClass cls = MyClass.findById(someLongId)
cls.setSurname("Marley");
cls.update();
So this triggers the preUpdate method in mylistener and when I try to :
MyClass.findById(someLongId);
When I debug I already get the newly updated instance but the update hasn't happened yet because when I check in database in column surname it's still Dylan.
How do I get the value from database in my MyListener0 method and not the one I just updated?
|
Getting object field previous value hibernate JPA
|
I know I'm late, but I have recently been looking for a way to store web pages for offline reading, and still could't find any reliable solution that wouldn't depend on the page itself and wouldn't use the deprecated UIWebView. A lot of people write that one should use the existing HTTP caching, but WebKit seems to do a lot of stuff out-of-process, making it virtually impossible to enforce complete caching (see here or here). However, this question guided me into the right direction. Tinkering with the web archive approach, I found that it's actually quite easy to write your own web archive exporter.
As written in the question, web archives are just plist files, so all it takes is a crawler that extracts the required resources from the HTML page, downloads them all and stores them in a big plist file. This archive file can then later be loaded into the WKWebView via loadFileURL(URL:allowingReadAccessTo:).
I created a demo app that allows archiving from and restoring to a WKWebView using this approach: https://github.com/ernesto-elsaesser/OfflineWebView
EDIT: The archive generation code is now available as standalone Swift package: https://github.com/ernesto-elsaesser/WebArchiver
The implementation only depends on Fuzi for HTML parsing.
|
We're trying to save the content (HTML) of WKWebView in a persistent storage (NSUserDefaults, CoreData or disk file). The user can see the same content when he re-enters the application with no internet connection. WKWebView doesn't use NSURLProtocol like UIWebView (see post here).
Although I have seen posts that "The offline application cache is not enabled in WKWebView." (Apple dev forums), I know that a solution exists.
I've learned of two possibilities, but I couldn't make them work:
1) If I open a website in Safari for Mac and select File >> Save As, it will appear the following option in the image below. For Mac apps exists [[[webView mainFrame] dataSource] webArchive], but on UIWebView or WKWebView there is no such API. But if I load a .webarchive file in Xcode on WKWebView (like the one I obtained from Mac Safari), then the content is displayed correctly (html, external images, video previews) if there is no internet connection. The .webarchive file is actually a plist (property list). I tried to use a mac framework that creates a .webarchive file, but it was incomplete.
2) I obtanined the HTML in webView:didFinishNavigation but it doesn't save external images, css, javascript
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
completionHandler: { (html: AnyObject?, error: NSError?) in
print(html)
})
}
We're struggling over a week and it is a main feature for us.
Any idea is really appreciated.
Thank you!
|
Swift iOS Cache WKWebView content for offline view
|
The best way to save data when you want to repopulate it at a later point of time is to save it in localStorage, which allows you to get the data even after refreshing the app
const InitialState = {
someState: 'a'
}
class App extends Component {
constructor(props) {
super(props);
// Retrieve the last state
this.state = localStorage.getItem("appState") ? JSON.parse(localStorage.getItem("appState")) : InitialState;
}
componentWillUnmount() {
// Remember state for the next mount
localStorage.setItem('appState', JSON.stringify(this.state));
}
render() {
...
}
}
export default App;
|
I know, using Redux I have common store and when I change my location, for example I went from /videos page, but I still have fetched videos in my videos reducer. So if I then decide to go back to my videos page I show user already loaded videos from my store, and will load more if he needs and store them.
But in React without Redux if I change my location /videos where I fetched some videos and then stored them in my local state of my VideosPage component and then went back to this page, I have no videos anymore and should fetch them from scratch.
How can I cache them and is it possible at all?
PS: This is more theoretical question so no code provided.
|
How to cache fetched data in react without redux
|
Guava's wiki documentation has a full definition of it: (emphasis is mine)
A LoadingCache is a Cache built with an attached CacheLoader. Creating a CacheLoader is typically as easy as implementing the method V load(K key) throws Exception. So, for example, you could create a LoadingCache with the following code:
[...]
The canonical way to query a LoadingCache is with the method get(K). This will either return an already cached value, or else use the cache's CacheLoader to atomically load a new value into the cache. Because CacheLoader might throw an Cache0, Cache1 throws Cache2. If you have defined a Cache3 that does not declare any checked exceptions then you can perform cache lookups using Cache4; however care must be taken not to call Cache5 on caches whose Cache6s declare checked exceptions.
The sentence emphasized explains all there is to explain: a value is either taken from the cache or loaded when Cache7 is called.
In the comments you said you want more emphasis on what is loading. When you put things in the cache, you put. When you don't put things in the cache, but the cache will compute and put it itself, the cache loads it for you.
|
Google offers a "loading cache", which is described as following:
A semi-persistent mapping from keys to values. Values are automatically loaded by the cache, and are stored in the cache until either evicted or manually invalidated.
Unfortunately, the description above isn't terribly clear. what does it mean to be "automatically loaded"?
I'm hoping it means: "If a requested key does not exist in the cache, it is then added to it automatically".
this is somewhat supported by this statement (from the get() function):
"Returns the value associated with in this cache, first loading that
value if necessary."
but again, the "loading" aspect of the cache is explained with the word "loading". way to go, Google :[
|
What is a "LoadingCache"?
|
15
Cache - By definition means it is stored in memory. Any data stored in memory (RAM) for faster access is called cache. Examples: Ehcache, Memcache Typically you put an object in cache with String as Key and access the cache using the Key. It is very straight forward. It depends on the application when to access the cahce vs database and no complex processing happens in the Cache. If the cache spans multiple machines, then it is called distributed cache. For example, Netflix uses EVCAche which is built on top of Memcache to store the users movie recommendations that you see on the home screen.
In Memory Database - It has all the features of a Cache plus come processing/querying capabilities. Redis falls under this category. Redis supports multiple data structures and you can query the data in the Redis ( examples like get last 10 accessed items, get the most used item etc). It can span multiple machine and is usually very high performant and also support persistence to disk if needed. For example, Twitter uses Redis database to store the timeline information.
Share
Improve this answer
Follow
answered Dec 14, 2018 at 15:18
VimalKumarVimalKumar
1,70011 gold badge1414 silver badges1111 bronze badges
Add a comment
|
|
I was wondering if I could get an explanation between the differences between In-Memory cache(redis, memcached), In-Memory data grids (gemfire) and In-Memory database (VoltDB). I'm having a hard time distinguishing the key characteristics between the 3.
|
Difference between In-Memory cache and In-Memory Database
|
I've got similar requirements to you - concurrency (on 2 hexacore CPUs) and LRU or similar - and also tried Guava MapMaker. I found softValues() much slower than weakValues(), but both made my app excruciatingly slow when memory filled up.
I tried WeakHashMap and it was less problematic, oddly even faster than using LinkedHashMap as an LRU cache via its removeEldestEntry() method.
But by the fastest for me is ConcurrentLinkedHashMap which has made my app 3-4 (!!) times faster than any other cache I tried. Joy, after days of frustration! It's apparently been incorporated into Guava's MapMaker, but the LRU feature isn't in Guava r07 at any rate. Hope it works for you.
|
I need to cache objects in Java using a proportion of whatever RAM is available. I'm aware that others have asked this question, but none of the responses meet my requirements.
My requirements are:
Simple and lightweight
Not dramatically slower than a plain HashMap
Use LRU, or some deletion policy that approximates LRU
I tried LinkedHashMap, however it requires you to specify a maximum number of elements, and I don't know how many elements it will take to fill up available RAM (their sizes will vary significantly).
My current approach is to use Google Collection's MapMaker as follows:
Map<String, Object> cache = new MapMaker().softKeys().makeMap();
This seemed attractive as it should automatically delete elements when it needs more RAM, however there is a serious problem: its behavior is to fill up all available RAM, at which point the GC begins to thrash and the whole app's performance deteriorates dramatically.
I've heard of stuff like EHCache, but it seems quite heavy-weight for what I need, and I'm not sure if it is fast enough for my application (remembering that the solution can't be dramatically slower than a HashMap).
|
How do I efficiently cache objects in Java using available RAM?
|
I've reduced the amount of stutter on my animations by following these rules listed in order of importance when reducing stutter:
Don't initiate animations in onCreate, onStart or onResume.
Initiate animations on user events such as onClick and disable touch events until animation is complete.
Don't initiate more than 2 animations simultaneously.
|
So I've been having animation issues especially when two animations happen at once or right when an activity loads. I understand it's probably a resource problem and a lot of things are going on in the main thread causing the animations to stutter.
I've found a couple interesting suggestions:
1. Threads (ThreadPoolExecutor)
Here: How do I make my animation smoother Android
2. setDrawingCacheEnabled(true)
Here: How does Android's setDrawingCacheEnabled() work?
3. ViewGroup: animationCache = true
Here: http://www.curious-creature.org/2010/12/02/android-graphics-animations-and-tips-tricks/
However I haven't been able to find any sort of examples to implement these things. Any ideas?
|
Android animation reduce stutter/choppy/lag
|
1
I can't see anything wrong with your configuration. As you know the important settings are in place:
default:
auto_eject_hosts: true
server_failure_limit: 1
The documentation suggests connection timeouts might be an issue.
Relying only on client-side timeouts has the adverse effect of the original request having timedout on the client to proxy connection, but still pending and outstanding on the proxy to server connection. This further gets exacerbated when client retries the original request.
Is your PHP script closing the connection and retrying before twemproxy failed its first attempt and removed the server from the pool? Perhaps adding a timeout value in the twemproxy lower than the connection timeout used in PHP solves the issue.
From your discussion on Github though it sounds like support for healthcheck, and perhaps auto ejection, aren't stable in twemproxy. If you're building against old packages you might be better to find a package which has been stable for some time. Is mcrouter (with interesting article) suitable?
Share
Improve this answer
Follow
answered Nov 12, 2015 at 13:43
NoChecksumNoChecksum
1,21611 gold badge1414 silver badges3131 bronze badges
2
I tried various permutations. I unset the memcached object, added a sleep, then reinstantiated the object. But still no luck. I am quite certain I tweaked the timeout setting, but it's not in the OP, I need to check my notes. I'll update.
– Mike Purcell
Nov 12, 2015 at 16:04
I updated config in OP, I do have timeout set to 100 (ms). Which should pass by at least the 3rd try.
– Mike Purcell
Nov 12, 2015 at 16:55
Add a comment
|
|
Simple setup:
1 node running twemproxy (vcache:22122)
2 nodes running memcached (vcache-1, vcache-2) both listening on 11211
I have the following twemproxy config:
default:
auto_eject_hosts: true
distribution: ketama
hash: fnv1a_64
listen: 0.0.0.0:22122
server_failure_limit: 1
server_retry_timeout: 600000 # 600sec, 10m
timeout: 100
servers:
- vcache-1:11211:1
- vcache-2:11211:1
The twemproxy node can resolve all hostnames. As part of testing I took down vcache-2. In theory for every attempt to interface with vcache:22122, twemproxy will contact a server from the pool to facilitate the attempt. However, if one of the cache nodes is down, then twemproxy is supposed to "auto eject" it from the pool, so subsequent requests will not fail.
It is up to the app layer to determine if a failed interface attempt with vcache:22122 was due to infrastructure issue, and if so, try again. However I am finding that on the retry, the same failed server is being used, so instead of subsequent attempts being passed to a known good cache node (in this case vcache-1) they are still being passed to the ejected cache node (vcache-2).
Here's the php code snippet which attempts the retry:
....
// $this is a Memcached object with vcache:22122 in the server list
$retryCount = 0;
do {
$status = $this->set($key, $value, $expiry);
if (Memcached::RES_SUCCESS === $this->getResultCode()) {
return true;
}
} while (++$retryCount < 3);
return false;
-- Update --
Link to Issue opened on Github for more info: Issue #427
|
Twitter - twemproxy - memcached - Retry not working as expected
|
I ended up manually clearing the entire cache by going into the rails console and using the command:
Rails.cache.clear
|
I'm using Memcached with Heroku for a Rails 3.1 app. I had a bug and the wrong things are showing - the parameters were incorrect for the cache.
I had this:
<% cache("foo_header_cache_#{@user.id}") do %>
I removed the fragment caching and pushed to Heroku and the bad data went away.
And then I changed it to:
<% cache("foo_header_cache_#{@foo.id}") do %>
However, when I corrected the parameters, from @user to @foo, the old [incorrect] cached version showed again (instead of refreshing with the correct data).
How can I manually expire this, or otherwise get rid of this bad data that is showing?
|
Manually Clear Fragment Cache in Rails
|
65
You can use your criteria as query key. Whenever a query's key changes, the query will automatically update.
const FetchPosts = async ({criteria}) => {
console.log(criteria) //from useQuery key
//your get api call here with criteria params
return posts;
};
const [criteria, setCriteria] = useState("")
const {isLoading, data: post} = useQuery(["posts", criteria], FetchPosts); //include criteria state to query key
console.log(post)
<select
name="filter"
value={criteria}
onChange={(e) => {
setCriteria(e.target.value); // trigger a re-render and cause the useQuery to run the query with the newly selected criteria
}}
>
<option>Most recent First</option>
<option>Price: Low to High</option>
<option>Price: High to Low</option>
</select>
Share
Improve this answer
Follow
answered Nov 14, 2020 at 6:59
ChanandreiChanandrei
2,34133 gold badges1111 silver badges1919 bronze badges
4
1
I have a different use case. How do I NOT fire the useQuery on every criterion change? I only want to fetch during the initial render and when an action is triggered (ex: Apply Filter button click)
– TA3
May 14, 2021 at 5:46
@TA3 I have the same doubt, any solutions?
– asds_asds
Jun 25, 2021 at 19:54
@TA3 and @asds_asds If you don't set your parameter as part of the query key, your query will not fire on criterion changes. For example: useQuery("thisIsAStaticKey", doSomething());
– IamButtman
Apr 26, 2022 at 18:32
Thanks man! Can I also do this for multiple arrays?
– Bon Andre Opina
Sep 28, 2022 at 9:41
Add a comment
|
|
I have a select option menu. So, When a user selects an option, I want send a GET/ request to the server with that option and recieve the filtered data from server.
This can be achived using useEffect(() => {// send the request}, [criteria])
Because, useEffect ensures that the request will send to server only if the setCriteria is finished.
But, I am using react-query library. so that, it is not allowed to use useQuery inside useEffect.
As A result, the request is send to server before it the setState is completed.
So that, server gets the previous selected value, not the currently selected value.
onChange:
<select
name="filter"
value={criteria}
onChange={async (e) => {
setCriteria(e.target.value);
}}
>
<option>Most recent First</option>
<option>Price: Low to High</option>
<option>Price: High to Low</option>
</select>;
Fetch posts:
const FetchPosts = async () => {
const {
data: { posts },
} = await axios.get(`${process.env.API_URL}/api/posts`, {
params: {
filter: criteria,
},
});
return posts;
};
useQuery("posts", FetchPosts);
const posts = queryCache.getQueryData("posts");
|
react-query: Refetch Query only if the state variable is changed
|
I just used a scheduled task to clear all cache using the cache manager.
@Component
public class ClearCacheTask {
@Autowired
private CacheManager cacheManager;
@Scheduled(fixedRateString = "${clear.all.cache.fixed.rate}", initialDelayString = "${clear.all.cache.init.delay}") // reset cache every hr, with delay of 1hr after app start
public void reportCurrentTime() {
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
}
}
Gets the job done.
|
On app start, I initialized ~20 different caches:
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(many many names));
return cacheManager;
}
I want to reset all the cache at an interval, say every hr. Using a scheduled task:
@Component
public class ClearCacheTask {
private static final Logger logger = LoggerFactory.getLogger(ClearCacheTask.class);
private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
@Value("${clear.all.cache.flag}")
private String clearAllCache;
private CacheManager cacheManager;
@CacheEvict(allEntries = true, value="...............")
@Scheduled(fixedRate = 3600000, initialDelay = 3600000) // reset cache every hr, with delay of 1hr
public void reportCurrentTime() {
if (Boolean.valueOf(clearAllCache)) {
logger.info("Clearing all cache, time: " + formatter.print(DateTime.now()));
}
}
}
Unless I'm reading the docs wrong, but @CacheEvict requires me to actually supply the name of the cache which can get messy.
How can I use @CacheEvict to clear ALL caches?
I was thinking instead of using @CacheEvict, I just loop through all the caches:
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
|
How can I evict ALL cache in Spring Boot?
|
The easiest way is to append the source string with some random parameter, which gets ignored on the server side
<script src="mySaveFiles.json?nocache=123" ></script>
One solution would be to generate the script element using JavaScript and append the current time like this:
var el = document.createElement( script );
el.src = 'mySaveFiles.json?nocache=' + (new Date()).getTime();
document.head.appendChild( el );
That way, the browser will never cache the JSON-file as it appears to be a different file (due to the parameter) in every call.
|
So I'm making this little project and I'm having some troubles with catching. One thing that's not working is the browser keeps caching the json file that contains save data and when I update the json somewhere else, the browser goes back to the old version of the json file that it has cached and reads off that. Unfortunately I dont want that. I dont want the browser to cache the file at all so that every time it loads up the page, it'll ask the server for the json file and act according to that file instead of whatever file that it has cached. I would however like to be able to cache all the other stuff that's on the page but if that has to be sacrificed for this to work then it's a sacrifice I'm willing to make. I'm envisioning that in JavaScript that there would be a call that says discard the current json file and go ask the server again for it or something like
<script src="mySaveFiles.json" cache="no">
or something of the sort to help me achieve what I'm talking about... help?
|
How to prevent the browser from caching a json file
|
Your question contains several separate questions together. Let's start slowly. ServletContext is good place where you can store handle to your cache. But you pay by having cache per server instance. It should be no problem. If you want to register cache in wider range consider registering it into JNDI.
The problem with caching. Basically, you are retrieving xml via webservice. If you are accesing this webservice via HTTP you can install simple HTTP proxy server on your side which handle caching of xml. The next step will be caching of resolved xml in some sort of local object cache. This cache can exists per server without any problem. In this second case the EHCache will do perfect job. In this case the chain of processing will be like this Client - http request -> servlet -> look into local cache - if not cached -> look into http proxy (xml files) -> do proxy job (http to webservice).
Pros:
Local cache per server instance, which contains only objects from requested xmls
One http proxy running on same hardware as our webapp.
Possibility to scale webapp without adding new http proxies for xml files.
Cons:
Next level of infrastructure
+1 point of failure (http proxy)
More complicated deployment
Update: don't forget to always send HTTP HEAD request into proxy to ensure that cache is up to date.
|
I am developing a Java web application that bases it behavior through large XML configuration files that are loaded from a web service. As these files are not actually required until a particular section of the application is accessed, they are loaded lazily. When one of these files are required, a query is sent to the webservice to retrieve the corresponding file. As some of the configuration files are likely to be used much, much more often than others I'd like to setup some kind of caching (with maybe a 1 hour expiration time) to avoid requesting the same file over and over.
The files returned by the web service are the same for all users across all sessions. I do not use JSP, JSF or any other fancy framework, just plain servlets.
My question is, what is considered a best practice to implement such a global, static cache within a java Web application? Is a singleton class appropriate, or will there be weird behaviors due to the J2EE containers? Should I expose something somewhere through JNDI? What shall I do so that my cache doesn't get screwed in clustered environments (it's OK, but not necessary, to have one cache per clustered server)?
Given the informations above, Would it be a correct implementation to put an object responsible for caching as a ServletContext attribute?
Note: I do not want to load all of them at startup and be done with it because that would
1). overload the webservice whenever my application starts up
2). The files might change while my application is running, so I would have to requery them anyway
3). I would still need a globally accessible cache, so my question still holds
Update: Using a caching proxy (such as squid) may be a good idea, but each request to the webservice will send rather large XML query in the post Data, which may be different each time. Only the web application really knows that two different calls to the webservice are actually equivalent.
Thanks for your help
|
Java Web Application: How to implement caching techniques?
|
39
You can use this code by this strategy Picasso will look for images in cache and if it failed only then image will be downloaded over network.
Picasso.with(context)
.load(Uri.parse(getItem(position).getStoryBigThumbUrl()))
.networkPolicy(NetworkPolicy.OFFLINE)
.into(holder.storyBigThumb, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
// Try again online if cache failed
Picasso.with(context)
.load(Uri.parse(getItem(position)
.getStoryBigThumbUrl()))
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(holder.storyBigThumb);
}
});
Share
Improve this answer
Follow
answered Dec 2, 2015 at 19:30
Hitesh SahuHitesh Sahu
43.3k1717 gold badges209209 silver badges157157 bronze badges
2
1
Perfect solution for someone who wants an image caching library! :)
– Zain
Apr 3, 2017 at 12:31
2
No need to write this much :) You can specify multiple network policies. For example .networkPolicy(NetworkPolicy.OFFLINE, NetworkPolicy.NO_CACHE) should have a similar behaviour to your code
– Alex Ionescu
Dec 9, 2018 at 0:30
Add a comment
|
|
I have some images that I download from different web sites when the app starts, by doing this:
Picasso.with(context).load(image_url).fetch();
Now, suppose the user closes the app and turns offline. When the app starts again, Picasso display the images in this way:
Picasso.with(ctx).load(image_url).placeholder(R.drawable.ph).into(imageView);
The problem is that some images are loaded from the disk cache (yellow triangle in debug mode), and for the others Picasso shows the placeholder.
Why? I'm expecting that every image is loaded from the disk cache.
|
Load images from disk cache with Picasso if offline
|
This website and this website contain information on the same problem. In order to keep your tables up to date, you must commit your transactions. Use db.commit() to do this.
As mentioned by the post below me, you can remove the need for this by enabling auto-commit. this can be done by running db.autocommit(True)
Also, auto-commit is enabled in the interactive shell, so this explains why you didn't have the problem there.
|
My Python program queries a set of tables in a MySQL DB, sleeps for 30 seconds, then queries them again, etc. The tables in question are continuously updated by a third-party, and (obviously) I would like to see the new results every 30 seconds.
Let's say my query looks like this:
"select * from A where A.key > %d" % maxValueOfKeyFromLastQuery
Regularly I will see that my program stops finding new results after one or two iterations, even though new rows are present in the tables. I know new rows are present in the tables because I can see them when I issue the identical query from interactive mysql (i.e. not from Python).
I found that the problem goes away in Python if I terminate my connection to the database after each query and then establish a new one for the next query.
I thought maybe this could be a server-side caching issue as discussed here: Explicit disable MySQL query cache in some parts of program
However:
When I check the interactive mysql shell, it says that caching is on. (So if this is a caching problem, how come the interactive shell doesn't suffer from it?)
If I explicitly execute SET SESSION query_cache_type = OFF from within my Python program, the problem still occurs.
Creating a new DB connection for each query is the only way I've been able to make the problem go away.
How can I get my queries from Python to see the new results that I know are there?
|
Chronic stale results using MySQLdb in Python
|
the sessionFactory provides the methods you want...
from the 19.3 chapter of the NHibernate reference:
To completely evict all objects from the session cache, call ISession.Clear()
For the second-level cache, there are methods defined on ISessionFactory for evicting the cached state of an
instance, entire class, collection instance or entire collection role.
sessionFactory.Evict(typeof(Cat), catId); //evict a particular Cat
sessionFactory.Evict(typeof(Cat)); //evict all Cats
sessionFactory.EvictCollection("Eg.Cat.Kittens", catId); //evict a particular collection of kittens
sessionFactory.EvictCollection("Eg.Cat.Kittens"); //evict all kitten collections
|
I just started thinking about using the NHibernate second level cache in one of my apps. I would probably use the NHibernate.Caches.SysCache.SysCacheProvider which relies on ASP.net cache.
Enabling the cache was not a problem, but I am wondering on how to manage the cache e. g. programmatically removing certain entities from the cache etc.
My application is some kind of image database. The user uploads images over a backend and can view it in the frontend by accessing /ImageDb/Show?userId=someUserId
The data does not change very often. And if it changes, the users would not matter a button named "clear my cache" in the backend that removes the cached objects for this user from the cache.
I found a solution online that can remove all cached objects from nhibernates second level cache. But thats a bit too brute force for me ... I dont want to clear the whole cache for dozens of users just because one user tried to clear the cache for his own data.
So what I basically wanted to do: selectively remove cached db objects from nhibernates second level cache in C#.
Is this possible? I guess it also depends on the cache provider. If this is not doable with the ASP.net cache provider, I am open for other built in / open source suggestions.
|
Removing objects from NHibernate second level cache
|
require.cache is just an exposed cache object reference, this property is not used directly, so changing it does nothing. You need to iterate over keys and actually delete them.
|
I am trying to delete a module from cache as suggested here.
In the documentation we read:
require.cache
Object
Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.
So, I created a file named 1.js that contains a single line:
module.exports = 1;
Then I require it via node shell:
ionicabizau@laptop:~/Documents/test$ node
> require("./1")
1
> require.cache
{ '/home/ionicabizau/Documents/test/1.js':
{ id: '/home/ionicabizau/Documents/test/1.js',
exports: 1,
parent:
{ id: 'repl',
exports: [Object],
parent: undefined,
filename: '/home/ionicabizau/Documents/test/repl',
loaded: false,
children: [Object],
paths: [Object] },
filename: '/home/ionicabizau/Documents/test/1.js',
loaded: true,
children: [],
paths:
[ '/home/ionicabizau/Documents/test/node_modules',
'/home/ionicabizau/Documents/node_modules',
'/home/ionicabizau/node_modules',
'/home/node_modules',
'/node_modules' ] } }
# edited file to export 2 (module.exports = 2;)
> require.cache = {}
{}
> require.cache
{}
> require("./1") // supposed to return 2
1
So, why does require("./1") return 1 when my file contains module.exports = 2 and the cache is cleared?
Doing some debugging I saw that there is a Module._cache object that is not cleared when I do require.cache = {}.
|
Clearing require cache
|
When you recycle the AppPool, there is some overlap time. Your unhealthy worker process is marked for recycling, but continues to handle requests that it has already received. (It will not handle new requests). The unhealthy worker will be terminated once all its existing requests are handled.
With IIS reset, all workers are terminated and the cache in memory is cleared. New workers will be created once new requests come in.
So I think that for both an AppPool recycle and an IIS reset will clear the cache. As for as I know, that cache is stored in the Application domain. Once the unhealthy worker process terminates, all cache items should be destroyed.
|
I have encountered a weird problem: as far as I know, cache can be cleared by recycling the application pool.
However, in a recent project, cache is not cleared in that way. Instead we had to reset IIS to clear the cache.
What are the differences between these actions, and what might be the cause of the differences I've experienced?
|
What is the difference between IIS reset and application pool recyle in affecting of cache
|
Something nice like would be wishful thinking.
Indeed, there is something you can do from within the link: Add a random GET parameter.
<a href="http://example.com/myfile.txt?a=193834923283943842923">View!</a>
You could use JavaScript (or of course a server-side scripting language like PHP) to do this on a dynamic basis.
However, the far superior way would be to configure the text file's caching headers correctly in the first place on server side. Stealing the header info from Best way to disable client caching, a .htaccess file like this should work:
<Files myfile.txt>
FileETag None
<IfModule mod_headers.c>
Header unset ETag
Header set Cache-Control "store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"
Header set Expires "Sun, 19 Nov 1978 05:00:00 GMT"
</IfModule>
</FilesMatch>
|
I have a file that I link to from my website like
<a href="http://example.com/myfile.txt>View!</a>
However, this file changes very frequently and when the link is clicked, the browser loads the cached version of the file, not the actual file.
Is there a way so that clicking on that link will bypass the cache for that page?
Something nice like <a bypassCache href=""> would be wishful thinking.
|
HTML link that bypasses cache?
|
The EF context will cache "per instance". That is, each instance of the DbContext keeps it's own independent cache of objects. You can store the resulting list of objects in a static list and query it all you like without returning to the database. To be safe, make sure you abandon the DbContext after you execute the query.
var dbContext = new YourDbContext();
StaticData.CachedListOfThings = dbContext.ListOfThings.ToList();
You can later use LINQ to query the static list.
var widgets = StaticData.CachedListOfThing.Where(thing => thing.Widget == "Foo");
The query executes the in-memory collection, not the database.
|
Say I have a table or 2 that contains data that will never or rarely change, is there any point of trying to cache those data? Or will the EF context cache that data for me when I load them the first time? I was thinking of loading all the data from those tables and use a static list or something to keep that data in memory and query the in memory data instead of the tables whenever I need the data within the same context. Those tables I speak of contains typically a few hundred rows of data.
|
Entity Framework 4 and caching of query results
|
In your root's .htaccess:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType image/x-icon "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
ExpiresByType text/html "access plus 600 seconds"
ExpiresByType application/xhtml+xml "access plus 600 seconds"
</IfModule>
And follow by:
<IfModule mod_headers.c>
<FilesMatch "\\.(ico|jpe?g|png|gif|swf)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(css)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(js)$">
Header set Cache-Control "max-age=216000, private"
</FilesMatch>
<FilesMatch "\\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</FilesMatch>
Header unset ETag
Header unset Last-Modified
</IfModule>
This is the exact same code I use on every property I manage and offers me (and PageSpeed) the most satisfying results. One may argue on specific rules, that's why I said that it satisfies me, but it certainly satisfies PageSpeed.
|
I ran tests on my website using Google's PageSpeed and it recommends that I "Leverage browser caching" and provided the following resource:
http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching
This resource never explains how to actually change the expiration date of my http headers. Do I do this through .htaccess? I would like to set the caching for as long as possible (without violating Google's policy of a year max).
Any advice on recommended settings (for a custom php-driven social networking community) would be greatly appreciated.
|
Set HTTP Caching Expiration, Recommended by Google PageSpeed
|
Have you tried flush_all() function? Docs here. You'll need a bit of logic & state to detect a new deployment or have a special script to perform the flushing.
Updated: look at the absolute path of one of your script: this changes on every deployment. You can use http://shell.appspot.com/ to experiment:
import sys
sys.path
['/base/python_dist/lib/python25.zip',
'/base/python_lib/versions/third_party/django-0.96',
'/base/python_dist/lib/python2.5/',
'/base/python_dist/lib/python2.5/plat-linux2',
'/base/python_dist/lib/python2.5/lib-tk',
'/base/python_dist/lib/python2.5/lib-dynload',
'/base/python_lib/versions/1',
'/base/data/home/apps/shell/1.335852500710379686/']
Look at the line with /shell/1.335852500710379686/.
So, just keep a snapshot (in memcache ;-) of this deployment state variable and compare in order to effect a flushing action.
Updated 2: as suggested by @Koen Bok, the environment variable CURRENT_VERSION_ID can be used also (part of the absolute path to script files also).
import os
os.environ["CURRENT_VERSION_ID"]
|
The title asks it all. The content on the site I'm building wont change very quickly at all and so Memcache could potentially store data for months except for when I put up an update. Is there a way to make it clear the cache every time I deploy the site? I'm using the Python runtime.
Update 1
Using jldupont's answer I put the following code in my main request handling script...
Update 2
I've switched to the method mentioned by Koen Bok in the selected answer's comments and prefixed all my memcache keys with os.environ['CURRENT_VERSION_ID']/ with the helpful code in the answer's 2nd update. This solution seems to be much more elegant than the function I posted before.
|
How can I have Google App Engine clear memcache every time a site is deployed?
|
You could always profile your application to see where it spends most of the time.
You can learn a lot about your application's behaviour and data access patterns this way.
If you are using Linux, you have a wide range of available tools for profiling, like:
OProfile
sysprof
valgrind + kcachegrind
EDIT:
For a more exact measurement of the processor performance as well as memory accesses, you could also try the AMD CodeAnalyst Performance Analyzer. Here are instructions on how to use it with Intel processors, though I haven't tried it myself.
Another tool that you might also find useful is the Intel Performance Tuning Utility.
|
I've got an application that does few computational CPU work, but mostly memory accesses (allocating objects and moving them around, there's few numeric or arithmetic code).
How can I measure the share of the time that am I spending in memory access latencies (due to cache misses), with the CPU being idle?
I should note that the app is running on a Hyper-V guest; I'm not sure it will pose any difficulties, but it might.
|
How to check if app is cpu-bound or memory-bound?
|
3
Try using the manifest storage instead:
class S3PipelineManifestStorage(PipelineMixin, ManifestFilesMixin, S3BotoStorage):
pass
According to the django docs here https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/#cachedstaticfilesstorage it's not recommended to use CachedStaticFilesStorage.
Your files names for your static files are probably getting cached. So use the manifest one.
CachedStaticFilesStorage isn’t recommended – in almost all cases ManifestStaticFilesStorage is a better choice. There are several performance penalties when using CachedStaticFilesStorage since a cache miss requires hashing files at runtime. Remote file storage require several round-trips to hash a file on a cache miss, as several file accesses are required to ensure that the file hash is correct in the case of nested file paths.
Note this is also documented at django-pipelines http://django-pipeline.readthedocs.io/en/latest/storages.html#using-with-other-storages
Share
Improve this answer
Follow
answered Jan 2, 2018 at 16:44
daloredalore
5,71411 gold badge3737 silver badges3838 bronze badges
Add a comment
|
|
Basically, the hash on the cache busting file is not updating.
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
PIPELINE_JS = {
'main.js': {
'output_filename': 'js/main.min.js',
'source_filenames': [
'js/external/underscore.js',
'js/external/backbone-1.0.0.js',
'js/external/bootstrap-2.2.0.min.js',
]
}
}
When I first ran the collectstatic command, it properly created a cache busting file named "main.min.d25bdd71759d.js
Now when I run the command, however, it is failing to overwrite that cached file (and update the hash) during the post process phase.
It keeps updating "main.min.js", such that main.min.js is current with my filesystem. A new cached file, however is not created. It keeps the same old hash even though the underlying main.min.js file has changed.
When I manually delete the cached file on AWS, I get the following message from running collectstatic with verbosity set to 3:
Post-processed 'js/main.min.js' as 'js/main.min.d25bdd71759d.js
settings.DEBUG is set to False
Why won't the hash update?
|
Django pipeline Cache Busting is not Updating Cached File/Hash
|
2
I have only been able to solve this problem by...
1: Stopping the Process
2: explicitly unregistering using regsvr32 the library ( or exename /unregserver)
3: Registering the new component
4: Starting the process back up.
I would suspect that it is the Un Reg part that is failing for you. If you are just changing the registry key directly then you should call RegSvr32 /u instead.
Also make sure the new directory location is the current directory when you call RegSvr32.
Note that I have always stopped the process and then unregistered, this is probably a significant detail.
Share
Improve this answer
Follow
answered Feb 21, 2013 at 10:09
Sql SurferSql Surfer
1,37411 gold badge1111 silver badges2626 bronze badges
Add a comment
|
|
Windows 7 is caching some of the COM class information. Older OSs didn't do this. After the OS looks up theHKCU\Software\Classes\CLSID\{GUID}\LocalServer32 value, it caches the value, and doesn't look it up again.
When we update our software, we place the new updates in a different directory, and then update the HKCU\Software\Classes\CLSID\{GUID}\LocalServer32 value to reflect the new path. The next time the software runs, it will use the latest files if running under older Windows OSs. However, on Windows 7, it will continue to use the older file, until the OS is rebooted.
I ran process monitor, and discovered that under Windows 7, it never reads the registry key again, after the first read. On older OSs, it reads that key every time.
My question is: Is there any way to force Windows 7 to re-read the LocalServer32 information from the HKCU hive each time a new out of proc COM object is created?
|
How to prevent Windows from caching Com Class info?
|
46
You can specify the maximum amount of physical memory dedicated to the MemoryCache in the application config file using the namedCaches element, or by passing in the setting when you create your MemoryCache instance via the NameValueCollection passed into the constructor by putting an entry in the collection with a key of cacheMemoryLimitMegabytes and a value of 10.
Here is an example of the namedCaches configuration element:
<configuration>
<system.runtime.caching>
<memoryCache>
<namedCaches>
<add name="Default"
cacheMemoryLimitMegabytes="10"
physicalMemoryLimitPercentage="0"
pollingInterval="00:05:00" />
</namedCaches>
</memoryCache>
</system.runtime.caching>
</configuration>
And here is how you can configure the MemoryCache during creation:
//Create a name / value pair for properties
var config = new NameValueCollection();
config.Add("pollingInterval", "00:05:00");
config.Add("physicalMemoryLimitPercentage", "0");
config.Add("cacheMemoryLimitMegabytes", "10");
//instantiate cache
var cache = new MemoryCache("CustomCache", config);
This blog post details just about all of the ways to configure the MemoryCache object, and some examples were adapted from this source.
Share
Improve this answer
Follow
edited Jul 24, 2013 at 12:37
Khonsort
48344 silver badges66 bronze badges
answered Apr 5, 2011 at 4:13
arcainarcain
15.1k66 gold badges5757 silver badges7575 bronze badges
2
1
When does this size limit get evaluated? When adding a new cache entry or only during the polling interval?
– Tamas Molnar
Jun 16, 2016 at 7:51
@manipurea async according to the pollingInterval and in concery=t with some complex gymnastics you can see if you take ILSpy to it
– Ruben Bartelink
Oct 24, 2017 at 9:36
Add a comment
|
|
I'm using .net 4 Memory Cache. I would like to limit the size of the cache say to 10mb because I don't want my application to be abusing what goes in there.
I would also like to know how much memory my cache is at any given time. How can I tell at run time?
|
Is there a way to enforce a size limit of MemoryCache in System.Runtime.Caching?
|
Using IIS management add a custom header Cache-Control with the value no-cache. That'll cause the browser to check that any cached version of the XAP is the latest before using it.
|
How to do I prevent a Silverlight XAP file being cached by the web browser?
The reason I want to do this is during development I don't want to manually clear the browser cache, I'm looking for a programmatic approach server side.
|
Making the Silverlight XAP file expire from browser cache programmatically
|
This problem arises in development mode when config.action_controller.perform_caching = true AND config.cache_classes = false -- it seems ActiveRecord objects cannot be stored with Rails.cache.
But if you need to enable config.action_controller.perform_caching in development mode for testing caching, then you must also enable config.cache_classes. This would be temporary, though, because then you'd have to restart the development server after changing classes or files in the asset pipeline.
With caching disabled, I would use Rails.cache.write(some_name, some_value) if Rails.env.production? to prevent caching from blowing up in development. Rails.cache.read() doesn't seem to be affected.
|
I'm implementing some caching by using the nifty Rails.cache.fetch. However, in one particular instance, sometimes I encounter an exception:
TypeError in EmloController#index
Emlo can't be referred to
app/controllers/emlo_controller.rb:320:in `get_employees'
app/controllers/emlo_controller.rb:356:in `prepare_json_response'
app/controllers/emlo_controller.rb:23:in `block (2 levels) in index'
app/controllers/emlo_controller.rb:15:in `index'
It seems the fetch will always explode (with the above) on the first try, and then work fine as long as the fetch is within the expiration. I know I'm missing something, so a fresh pair of eyes would be nice.
Here's the method which invokes the cache fetch:
def get_employees
# This is for a AJAX refresh loop, so a 5-second cache actually helps quite a bit
Rails.cache.fetch('emlo_all', :expires_in => 5.seconds, :race_condition_ttl => 1) do
conditions = (params[:id]) ? {:user_id => params[:id]} : nil
selections = [
'employee_locations.id AS emlo_id',
'employee_locations.status_id',
'employee_locations.notes',
'employee_locations.until',
'employee_locations.updated_at',
'employee_locations.user_id',
'location_states.id AS state_id',
'location_states.title AS status_string',
'location_states.font_color',
'location_states.bg_color',
'users.displayname',
'users.email',
'users.mobile',
'users.department',
'users.extension',
'users.guid',
'users.dn'
].join(', ')
Emlo.all(
:select => selections,
:joins => 'LEFT JOIN users ON employee_locations.user_id=users.id LEFT JOIN location_states ON employee_locations.status_id=location_states.id',
:conditions => conditions,
:order => 'users.displayname ASC'
)
end
end
|
Rails.cache.fetch exception: TypeError (<ModelName> can't be referred to)
|
CloudFront does now support wildcard or full distribution invalidation. You will need do do one of the followng.
Invalidate each object that has changed
Invalidate /*
Version your objects so that they are considered new (Ie rename or querystring)
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidating-objects-console
|
I made some changes to my origin server which now serves different data from same url.
I tried to clear my cache completely by doing the following invalidation in CF UI:
But this didn't work. How can I wipe off completely the Amazon CloudFront cache's in one go?
|
How to clear Amazon CloudFront Cache completely?
|
26
The default number of Redis databases is 16, but can be configured to more. You probably have 16 in your config because of that default (see Storing Data with Redis).
Databases (in Redis) are a way to partition data logically (think "namespace", "key-space" or, in RDBMS terms, a schema). Redis databases have nothing to do with scalability, so your "max limit" question is out of context.
To scale you would want to do as Sergio suggests in his comment: create separate Redis instances/clusters for separate applications.
Share
Improve this answer
Follow
answered Dec 27, 2018 at 21:11
KitKit
21k44 gold badges6262 silver badges105105 bronze badges
Add a comment
|
|
In redis, select "number" gives access to specific database at that index. I my redis config it is set 16(why ?). We require high scaling of our application so what is the max limit for that?
|
Maximum number of databases in redis
|
Create / edit your .htaccess file and add the following:
FileETag MTime Size
Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:
<?php
$file = 'myfile.php';
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
|
How do you implemented etags inside a PHP file? What do I upload to the server and what do I insert into my PHP file?
|
How to use etags in a PHP file?
|
We have used HttpContext.Current.Items collection to do RequestScope caching. It works well.
|
We using ASP.NET 3.5 (Controls-based approach) and need to have storage specific for one http request only.
Thread-specific cache with keys from session id won't work because threads are supposed to be pooled and therefore I have a chance to have data from some previous request in cache, which is undesirable in my case. I always need to have brand new storage for each request available through whole request.
Any ideas how to do it in ASP.NET 3.5?
|
How to make per- http Request cache in ASP.NET 3.5
|
34
If you plan on scaling your application in the future, you choose redis
If this is just a small project that you need good performance you go with in-memory.
As a starter I recommend to go with in-memory caching but use a inversion of control mechanism to be able to refactor easily this stuff after into using redis. Try something like this:
// cache service
module.exports = (provider) => {
// provider here is an abstraction of redis or in memory node
// implement your logic
const save = (key, item) => {
provider.save(key, item);
// return promise callback etc
}
const getItem = (key) => {
provider.get(key);
}
return {
save,
getItem,
}
}
And then you just use the needed provider and you can easily refactor the code after, no need to change all the files in your app.
Share
Improve this answer
Follow
edited Jun 20, 2020 at 9:12
CommunityBot
111 silver badge
answered Sep 5, 2017 at 7:38
Alexandru OlaruAlexandru Olaru
6,97066 gold badges2929 silver badges5454 bronze badges
Add a comment
|
|
I am planning to use a cache in my Node.js application just to avoid a database read operation. It is only some small amount of data (instead of reading same data from database every time) . I am planning to have a local cache in each server.
Should I go for Node Cache (https://www.npmjs.com/package/node-cache) or Redis ?
Which will be faster and efficient ?
|
Node-Cache vs Redis for Simple Caching
|
You can use the OBJECT IDLETIME command for this purpose. It returns the number of seconds since the key was accessed, but If you need the time just subtract the reply from now().
|
I'd like to view the time of most recent access for a specific key on my redis server.
I know that this information is stored for each key because it is used in redis's LRU algorithm for eliminating old keys.
Is there an easy way to see this information for a given key?
|
Get the last time a given Redis key was accessed
|
38
+100
Flush does write back the contents of cache to main memory, and invalidate does mark cache lines as invalid so that future reads go to main memory.
I think you would combine flush and invalidate if the device was updating a block of memory: the flush would ensure that the device had the latest contents, and the invalidate would then ensure that when the device had finished that the CPU would read the new contents from memory.
Share
Improve this answer
Follow
answered Feb 27, 2010 at 11:43
BCranBCran
1,9191919 silver badges1616 bronze badges
1
2
Adding for clarity, This is carried out mainly during initialization stage. The initialized descriptors are both Flushed(to update in memory) and Invalidated(So that next read by CPU is with useful contents) during initialization stage.
– kumar
Nov 23, 2014 at 11:55
Add a comment
|
|
I have some questions on cache synchronization operations.
Invalidate: Before cpu tries to read a portion of memory updated by a device, the corresponding memory needs to be invalidated.
Flush: Before the device read a portion of memory updated by CPU, CPU must flush (write back is also correct?) the contents from cache to memory, so that device reads the contents from memory with updated contents.
If flush is not carried out it may read junk data present in memory as the memory is not still updated with contents written to cache.
Please confirm whether my above understanding is correct?
When do you want to combine both flush and invalidate? I heard that while playing with device control descriptors we need to synchronize by combining flush and invalidate. Why so?
Do we need to follow a sequence like flush followed by invalidate?
Is there a scenario in which invalidate followed by flush will be useful?
|
cache - flush and invalidate operation
|
The default rails cache key format is: [class]/[id]-[timestamp]
i usually dont use rails default cache key format, instead i create my own keys so it would be easier to manipulate in redis.
cache_key = "#{self.class.name}/#{translated_attribute}/#{id}/#{field}/#{I18n.locale}"
Rails.cache.fetch(cache_key) do
self.read_attribute field, locale: I18n.locale
end
Rails.cache.delete(cache_key)
Rails.cache.delete_matched("#{self.class.name}*#{id}*")
|
I am using redis-rails. For cache key I am using an array:
Rails.cache.fetch([self.class.name, :translated_attribute, id, field, I18n.locale]) do
self.read_attribute field, locale: I18n.locale
end
Now I need to remove all the cache with key matches with [self.class.name, :translated_attribute, id]. I know it has delete_matched that takes wildcard(*) after key for partial matching.
But I dont know what is the exact key generated. Now I need to know how it makes the key when we use array as key. I mean if I use [:foo, :bar, :dum] as cache key what will be the exact key in cache store?
|
rails how to delete cache key using partial match
|
Just after writing the question started thinking about utility method powered with generics.
Then remembered something about Throwables.
And yes, it's already there! )
It may also be necessary to handle UncheckedExecutionException or even ExecutionError.
So the solution is:
public Post getPost(final Integer key) throws SQLException, IOException {
try {
return cache.get(key, new Callable<Post>() {
@Override
public Post call() throws Exception {
return PostsDB.findPostByID(key);
}
});
} catch (ExecutionException e) {
Throwables.propagateIfPossible(
e.getCause(), SQLException.class, IOException.class);
throw new IllegalStateException(e);
} catch (UncheckedExecutionException e) {
Throwables.throwIfUnchecked(e.getCause());
throw new IllegalStateException(e);
}
}
Very nice!
See also ThrowablesExplained, LoadingCache.getUnchecked and Why we deprecated Throwables.propagate.
|
I'm refactoring some code to use guava Cache.
Initial code:
public Post getPost(Integer key) throws SQLException, IOException {
return PostsDB.findPostByID(key);
}
In order not to break something I need to preserve any thrown exception as is, without wrapping it.
Current solution appears somewhat ugly:
public Post getPost(final Integer key) throws SQLException, IOException {
try {
return cache.get(key, new Callable<Post>() {
@Override
public Post call() throws Exception {
return PostsDB.findPostByID(key);
}
});
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof SQLException) {
throw (SQLException) cause;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new IllegalStateException(e);
}
}
}
Is there any possible way to make it nicer?
|
Guava cache and preserving checked exceptions
|
Each service is performing differently in different regions. Amazon CloudFront can be better in the APAC region, while Akamai might be better in South of Europe and the Middle east.
Since this is a physical service that depends on the actual location of their PoP (Point of Presence) servers, you need to measure where most of your users are, and choose the better service for that region.
You can see such a comparison about the CDN performance in different regions here: http://media.amazonwebservices.com/FS_WP_AWS_CDN_CloudFront.pdf
The main difference between CloudFront and Akamai is the number of PoP servers. CloudFront is using Super PoP approach, which means much fewer (edge) locations (54 as of January 2016 - see complete list here), compared to the thousands that Akamai has around the world. This is why CloudFront costs less than Akamai.
Having more PoP was crucial in the early days of the Internet. But as the Internet is developing around the world the difference in performance is shrinking.
There are even benefits for "Super PoP" in terms of cache, as there is a better chance of finding an element in the cache if you have fewer cache servers.
If you are hosting your web servers in EC2, you will probably get better performance and surely better pricing from CloudFront. If not, you should check the performance and pricing between the various providers.
Note that you don't have to be exclusive, as many big content providers are using several CDN and not a single one.
|
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 years ago.
Improve this question
What are the advantages of using Akamai vs. CloudFront? From what I've read, Akamai seems to be more expensive but they seem to have a larger network for their CDN. CloudFront on the other end is newer and Amazon even used Akamai for their e-commerce site when CloudFront was launched in 2008. This might have changed since then which will not surprise me.
I like CloudFront because my application will be hosted on AWS so there might be significant benefits from using CloudFront rather than Akamai. CloudFront seems to be better documented too and their API is easily accessible whereas Akamai isn't. I'm hoping to get pros and cons between choosing Akamai vs. CloudFront. Thanks in advance!
|
Akamai vs CloudFront [closed]
|
As Evans mentioned this headers should be set from the server side. How you actually set the headers differs between backend programming languages/servers.
Here are a few examples:
Node.js res.setHeader('Cache-Control', 'no-cache');
Nginx add_header Cache-Control no-cache;
|
I'm trying to follow the guidance on create-react-app.dev's Production Build documentation:
To deliver the best performance to your users, it's best practice to specify a Cache-Control header for index.html, as well as the files within build/static. This header allows you to control the length of time that the browser as well as CDNs will cache your static assets. If you aren't familiar with what Cache-Control does, see this article for a great introduction.
Using Cache-Control: max-age=31536000 for your build/static assets, and Cache-Control: no-cache for everything else is a safe and effective starting point that ensures your user's browser will always check for an updated index.html file, and will cache all of the build/static files for one year. Note that you can use the one year expiration on build/static safely because the file contents hash is embedded into the filename.
Is the correct way to do this to use HTML headers in index.html - eg something like:
<meta http-equiv="Cache-Control" content="max-age: 31536000, no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
(Credit: this stack overflow response and this YouTube tutorial)
If so, how do I follow the documentation's suggestion that I should set "max-age=31536000 for your build/static assets, and Cache-Control: no-cache for everything else"? I don't know how to set different controls for different assets.
|
How to specify a Cache-Control header for index.html in create-react-app
|
A pitfall: A static field is scoped per app domain, and increased load will make the server generate more app domains in the pool. This is not necessarily a problem if you only read from the statics, but you will get duplicate data in memory, and you will get a hit every time an app domain is created or recycled.
Better to use the Cache object - it's intended for things like this.
Edit: Turns out I was wrong about AppDomains (as pointed out in comments) - more instances of the Application will be generated under load, but they will all run in the same AppDomain. (But you should still use the Cache object!)
|
At the moment I am working on a project admin application in C# 3.5 on ASP.net. In order to reduce hits to the database, I'm caching a lot of information using static variables. For example, a list of users is kept in memory in a static class. The class reads in all the information from the database on startup, and will update the database whenever changes are made, but it never needs to read from the datebase.
The class pings other webservers (if they exist) with updated information at the same time as a write to the database. The pinging mechanism is a Windows service to which the cache object registers using a random available port. It is used for other things as well.
The amount of data isn't all that great. At the moment I'm using it just to cache the users (password hashes, permissions, name, email etc.) It just saves a pile of calls being made to the database.
I was wondering if there are any pitfalls to this method and/or if there are better ways to cache the data?
|
Is it OK to use static variables to cache information in ASP.net?
|
Steps for adding cache control for existing objects in your bucket
git clone https://github.com/s3tools/s3cmd
Run s3cmd --configure
(You will be asked for the two keys - copy and paste them from your
confirmation email or from your Amazon account page. Be careful when
copying them! They are case sensitive and must be entered accurately
or you'll keep getting errors about invalid signatures or similar.
Remember to add s3:ListAllMyBuckets permissions to the keys or you will get an AccessDenied error while testing access.)
./s3cmd --recursive modify --add-header="Cache-Control:public ,max-age= 31536000" s3://your_bucket_name/
For CloudFront you can specify Minimum TTL, Maximum TTL, and Default TTL for a cache behavior.they are basically the time for which an object can be cached on CloudFront and has nothing to do with adding an expiry header for the object i.e it doesn't mody any header
So now if you haven't added any header, then cloudfront will caches it for DEFAULT TTL.
FOR MORE INFO READFOLLOWING TABLE
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html#ExpirationDownloadDist
|
I have an amazon S3 bucket with approximately 300K items in it that are used by a large website. I would like to set the expiration of all the objects that are served out of CloudFront from the S3 bucket so that they can be cached in the browser by the user's machine. Is there an easy way to set the cache control on all the s3 objects currently in the bucket AND most importantly set a default for the bucket so that any new items added also gain the expires and cache-control headers OR can this be done using CloudFront?
So far i have read a number of AWS documents but have found nothing:
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
http://docs.aws.amazon.com/cli/latest/reference/s3/index.html
|
Set a default cache control and expires for entire S3 bucket/CloudFront
|
2
I believe the way I got around this was to create a fragment cache of the parts of the header that are dependent on the content_for being populated.
so it looks something like this:
# application.html.erb
<head>
<% cache("#{request.env['PATH_INFO']}/header") do %>
<title><%= yield(:page_title) %></title>
<% end %>
so this cached fragment should be populated at the same time the action is cached.
Share
Improve this answer
Follow
answered Mar 22, 2012 at 4:20
Andrew WrightAndrew Wright
11611 silver badge44 bronze badges
2
2
Don't do this, the two caches (action and your fragment) won't necessarily always be there, depending on your cache store. One might be pushed out of the cache or expired sooner. I am still looking for a good solution to this, though. What i'm doing now is patching the action caching to store these things such as title, etc in a hash, marshalling it, and caching that whole thing. HOWEVER this fails occasionally, and is driving me absolutely insane.
– XP84
Jun 9, 2012 at 5:35
Yes this is an important point, I currently use the file cache store and as such the two caches are stored in the same directory and I wipe the whole directory at once when clearing the cache for a record.
– Andrew Wright
Jul 11, 2012 at 18:45
Add a comment
|
|
When you use caches_action :layout => false in Rails 3, any content_for blocks that are populated in the cached view and used in your layout wind up empty. Is there any workaround for this?
E.g. in my application I have the following rather typical setup.
A helper method called from my views which sets the page title:
# application_helper.rb
def page_title(title)
content_for(:page_title) { title }
end
A line in my layout file as follows
# application.html.erb
<head>
<title><%= yield(:page_title) %></title>
</head>
And in a view I might call
# index.html
<% page_title 'Hello!' %>
Of course, if you cache your action with :layout => false, this results in having blank page titles, since action caching ignores all content_for blocks.
Is there no workaround for this? Action caching with :layout => false is so close to being brilliantly useful, but this glitch renders it quite awkward.
Other folks asking or commenting about this same issue:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/d8d72f050701d44b
http://www.golygon.com/2011/04/tips-and-tricks-in-ruby-on-rails/
https://rails.lighthouseapp.com/projects/8994/tickets/4140-action-caching-with-caches_action-and-layout-false
And the Rails documentation that notes this behavior:
"WARNING: content_for is ignored in caches. So you shouldn’t use it for elements that will be fragment cached."
|
Is there a workaround for ignored content_for blocks with caches_action and :layout => false?
|
1
Maybe it should be part of the Jersey Client itself. You can register interest here: JERSEY-100 The ticket is closed because "it has collected only 1 support votes and has not been updated" in 2015. I am "watching" this issue.
Share
Improve this answer
Follow
answered Mar 24, 2016 at 10:24
Meiko RachimowMeiko Rachimow
4,70422 gold badges2626 silver badges4343 bronze badges
1
The link you shared no more exist.
– Pawan
Oct 12, 2019 at 19:09
Add a comment
|
|
Jersey has wonderful support for server-side handling of Preconditions to respond to a Conditional-GET-request.
On the client-side it seems a bit less elegant/manual. As far as I know you'd need to store the metadata of the entity yourself (etag, last-modified header) and make a decision, when to set which headers, evaluate the response code, update your local cache of entity/metadata ... etc.
Do you know of a ready, free implementation that wraps up the conditonal GET? I found this example, where the poster is using CacheManager and CacheEntry; I suspect his own implementation. Shouldn't this be part of Jersey Client itself?
|
Jersey Client: Cache-Manager for Conditional GET?
|
Running git config --global -e allowed me to remove the offending config setting from the global git config.
[credential]
helper = winstore
|
After attempting to setup git credential cache on Windows 7 I would now like to scrap the idea and remove this error message and setting from git.
git: 'credential-cache' is not a git command.
This related question shows how to fix this error by installing additional software to make the credential caching work -- I however wish to remove this setting all together.
How do I do this?
I have tried:
git config --global --remove-section credential-cache and variations thereof.
Also it does not exist in my .git/config file either.
|
git: 'credential-cache' is not a git command - Remove setting
|
46
pip install 'Twisted<12.0'
As you can see in the requirements.txt, the newer version of Twisted does not seems to play well with it
Share
Improve this answer
Follow
edited May 23, 2014 at 21:51
Cheeso
191k103103 gold badges477477 silver badges718718 bronze badges
answered Nov 12, 2013 at 12:35
user120027user120027
58133 silver badges66 bronze badges
3
1
Works for me too. pip list | grep -i twist showed Twisted (14.0.0). When I did pip uninstall Twisted then installed Twisted<12.0, carbon was able to start.
– Cheeso
May 23, 2014 at 21:52
Solved the exact same issue as above – Ubuntu 12.04
– Ben
Jun 16, 2014 at 19:15
pip install Twisted==13.0
– mafrosis
Jun 25, 2014 at 5:11
Add a comment
|
|
I am really hoping someone can help me as I have spent at-least 15 hours trying to fix this problem. I have been given a task by a potential employer and my solution is to use graphite/carbon/collectd. I am trying to run and install carbon / graphite 0.9.12 but I simply can't get carbon to start. Every time I try and start carbon I end up with the following error. I am using a bash script to install to keep everything consistent.
I don't really know python at all so would appreciate any help you can provide.
/etc/rc0.d/K20carbon-cache -> ../init.d/carbon-cache
/etc/rc1.d/K20carbon-cache -> ../init.d/carbon-cache
/etc/rc6.d/K20carbon-cache -> ../init.d/carbon-cache
/etc/rc2.d/S20carbon-cache -> ../init.d/carbon-cache
/etc/rc3.d/S20carbon-cache -> ../init.d/carbon-cache
/etc/rc4.d/S20carbon-cache -> ../init.d/carbon-cache
/etc/rc5.d/S20carbon-cache -> ../init.d/carbon-cache
Traceback (most recent call last):
File "/opt/graphite/bin/carbon-cache.py",
line 28, in from carbon.util import run_twistd_plugin
File "/opt/graphite/lib/carbon/util.py",
line 21, in from twisted.scripts._twistd_unix import daemonize
ImportError: cannot import name daemonize
Thanks
Shane
|
Can't Start Carbon - 12.04 - Python Error - ImportError: cannot import name daemonize
|
Spring is pretty clear about TTL/TTI (Expiration) and Eviction policies as explained in the core Spring Framework Reference Guide here. In other words, the "defaults" depend entirely on the underlying data store (a.k.a. caching provider) used with the Spring Boot app via the Spring Cache Abstraction.
While Arpit's solution is a nice workaround and a generic, transferable solution across different caching providers (data stores), it also cannot cover more specific expiration/eviction policies, such as the kind of action to perform when an expiration/eviction, say OVERFLOW_TO_DISK, or LOCAL_DESTROY only (such as in a Highly Available (maybe zoned based), distributed scenario), or INVALIDATE, etc.
Usually, depending on the UC, evicting "all" entries is not an acceptable option and is one of the reasons why Spring delegates this responsibility to caching provider as this capability varies highly between 1 provider to another.
In summary... definitely review the requirements for your UC and pair the appropriate caching provider with the capabilities that match your UC. Spring supports a wide variety of caching providers from Redis to Apache Geode/Pivotal GemFire to Hazelcast, etc, each with different/similar capabilities in this regard.
|
I generally use the @Cacheable with a cache config in my spring-boot app and set specific TTL (time to live) for each cache.
I recently inherited a spring boot app that uses @Cacheable without explicitly stating a cache manager and ttl. I will be changing it to be explicit.
But I am not able to find out what are the defaults when there is nothing explicit.
I did look at the docs but found nothing there
|
Spring @Cacheable default TTL
|
I've just figured out how to achieve this.
Simply use the VaryByHeader property, set to "host". There are many possibilities to do so.
Method 1
Use the OutputCacheAttribute passing all the needed configuration elements, including VaryByHeader:
public class HomeController : Controller
{
[OutputCache(Duration = 3600, VaryByParam = "none", VaryByHeader = "host")]
public ActionResult Index() { /* ... */ }
}
Method 2.
Or you could set it to a profile on the Web.config:
<?xml version="1.0"?>
<configuration>
<!-- ... -->
<system.web>
<!-- ... -->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear/>
<add name="Multitenant"
enabled="true"
duration="3600"
varyByHeader="host"
varyByParam="none"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
</configuration>
Then use it:
public class HomeController : Controller
{
[OutputCache(CacheProfile = "Multitenant")]
public ActionResult Index() { /* ... */ }
}
Method 3.
Or you can subclass the OutputCacheAttribute and use it:
public sealed class MultitenantOutputCacheAttribute : OutputCacheAttribute
{
public MultitenantOutputCacheAttribute()
{
VaryByHeader = "host";
VaryByParam = "none";
Duration = 3600;
}
}
Then use it:
public class HomeController : Controller
{
[MultitenantOutputCache]
public ActionResult Index() { /* ... */ }
}
|
I have a multi-tenant application in ASP.NET MVC. The instance of the application that will be served is function of the hostname alone (something along the lines of stackexchange, I suppose).
Each instance of the application might have a different culture setting (even "auto", to read the browser's language and try to use it), and will be localized accordingly.
In this situation, I'd like to do some output caching on some of my actions. So, my questions are:
What are the possibilities to achieve output caching of a multi-tenant ASP.NET MVC application, if the output depends exclusively on the hostname (ie, ignoring the localization requirement)?
Same as (1), but now considering that the output depends on the culture settings as well?
Same as (2), but considering that the output might vary with parameters that were passed to the action?
In this case, I'm considering that all the sites run from a single IIS website.
|
Output cache for multi-tenant application, varying by hostname and culture
|
First, it appears you don't understand what the volatile keyword does. It makes sure that if the reference value held by the variable declared volatile changes, other threads will see it rather than having a cached copy. It has nothing to do with thread-safety in regard to accessing the HashMap
Given that, and the fact that you say the HashMap is read-only ... you certainly don't need to use anything that provides thread-safety including a ConcurrentHashMap
Edit to add: Your last edit you now say "The cache is being populated on a interval"
That's not read-only then, is it?
If you're going to have threads reading from it while you are writing (updating the existing HashMap) then you should use a ConcurrentHashMap, yes.
If you are populating an entirely new HashMap then assigning it to the existing variable, then you use volatile
|
I have a cache class which contains a volatile HashMap<T> to store cache items.
I'm curious what would be the consequences of changing volatile HashMap to ConcurrentHashMap?
Would i gain performance increase? This cache is readonly cache.
What would be the best option to use? just HashMap? Cache is being populated on a interval.
|
Volatile HashMap vs ConcurrentHashMap
|
Here are some things that I like consider when working on this kind of code.
Consider whether you want "structures of arrays" or "arrays of structures". Which you want to use will depend on each part of the data.
Try to keep structures to multiples of 32 bytes so they pack cache lines evenly.
Partition your data in hot and cold elements. If you have an array of objects of class o, and you use o.x, o.y, o.z together frequently but only occasionally need to access o.i, o.j, o.k then consider puting o.x, o.y, and o.z together and moving the i, j, and k parts to a parallel axillary data structure.
If you have multi dimensional arrays of data then with the usual row-order layouts, access will be very fast when scanning along the preferred dimension and very slow along the others. Mapping it along a space-filling curve instead will help to balance access speeds when traversing in any dimension. (Blocking techniques are similar -- they're just Z-order with a larger radix.)
If you must incur a cache miss, then try to do as much as possible with that data in order to amortize the cost.
Are you doing anything multi-threaded? Watch out for slowdowns from cache consistency protocols. Pad flags and small counters so that they'll be on separate cache lines.
SSE on Intel provides some prefetch intrinsics if you know what you'll be accessing far enough ahead of time.
|
How to decrease the number of possible cache misses when designing a C++ program?
Does inlining functions help every time? or is it good only when the program is CPU-bounded (i.e. the program is computation oriented not I/O oriented)?
|
decreasing cache misses through good design
|
Underlying Cache is likely a Hashtable or Dictionary<string, object>, whose getters do not differentiate between no value at that key, or a null value at that key.
Hashtable table = new Hashtable();
object x = table["foo"];
table.Add("foo", null);
object y = table["foo"];
Console.WriteLine(x == y); // prints 'True'
Consider a using placeholder "null" item, similar to DbNull.Value.
|
Can anyone explain why you cannot insert a null object into the ASP.NET cache?
string exampleItem = null;
HttpRuntime.Cache.Insert("EXAMPLE_KEY",
exampleItem,
Nothing,
DateTime.Now.AddHours(1),
System.Web.Caching.Cache.NoSlidingExpiration);
The exception error message states that the "value" object cannot be null. In my application there are valid reasons why we whould want to store a null value in the cache.
|
ASP.NET can't cache null value
|
from django.core.cache import cache
cache._cache.flush_all()
Also see this ticket, it has a patch (that I haven't tested) to flush any type of cache backend: http://code.djangoproject.com/ticket/11503
|
I don't want to restart the memcached server!
|
In Django, how to clear all the memcached keys and values?
|
SDWebImage does some caching by default, so it would be better to use a new URL if the image changes. So, for instance, if you have control over the URL and can change it every time the image has changed, you could do that.
If that's not the case, try using SDWebImageRefreshCached in the options field in order to respect HTTP cache control headers, like this:
[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
options:SDWebImageRefreshCached];
See more here
|
I am using SDWebImage library to download images from server.
https://github.com/rs/SDWebImage
SDWebImage not able update the cached image when image updated on server with the same url.
|
How to update image in cache when image changed on server with SDWebImage
|
Picasso uses the HTTP client for disk caching and if one is already configured it will use that instead of installing its own.
For the built-in UrlConnection the docs for installing a cache are here: https://developer.android.com/reference/android/net/http/HttpResponseCache.html
If you are using OkHttp then you just call setCache:
http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/OkHttpClient.html#setCache-com.squareup.okhttp.Cache-
|
I'm using picasso library to load images for my app. But I don't how to implement my own disk (sdcard) caching with picasso library.
|
How to implement my own disk cache with picasso library - Android?
|
I would disagree with you regarding Redis. Redis is a very powerful key-value store that can easily be used for what you want. It is designed to have stuff dumped in it and taken out again. In your situation, you can easy cache the API response by saving it into Redis with the query as the key (if this is a REST API you're calling, you could just use the URL or serialized data as the key) and simply cache the response as a stringified JSON object (or XML string if you happen to be getting that).
You can also set an expiry on the cached data, and it will be cleared when the time is expired.
You could then wrap your API call in a helper function which checks the cache, and returns the value if it's present. If it's not it makes the API request, adds it to the cache, then returns it.
This is probably the most straightforward solution and seems to cover your use case pretty well.
|
I am using node.js to write a web service, it calls an API for some data but I am limited by the API to a number of calls per month, so I wish to cache the data I retrieve from the API so I can serve it up with the cached data, and re-fetch the data from the API at a timed interval.
Is this a good approach for this problem? And what caching framework should I use? I looked at node-redis but I don't think a key value store is appropriate for the data.
Thanks!
|
Proper way to cache data from API call with nodejs
|
The #laravel IRC channel is a God send. This had nothing to do with Laravel's behavior at all. This was actually something PHP 5.5 was doing.
The reason this was so baffling is because I upgraded my PHP version from 5.3 and never had this issue.
In your .ini file, you need to tweak your OPcache settings. For me, these settings began at line 1087 in the .ini file and looked something like this:
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1
Take particular note of the opcache.revalidate_freq=60. This is what is actually making your views cache. If this is not the desired behavior, set the value to 0 and your views will update every time you make a change. Yay!
EDIT AUGUST 21, 2014
As mentioned by Matt below, make sure to restart your web server to see your changes take effect after you have changed your .ini file.
|
Some friends and I decided to start working on a project and we came across Laravel and thought it might be a good tool. We started using it locally to develop out some of our pages and noticed something strange.
When we update a view with different information, it would take almost 5 to 10 minutes before the views information would change. It's like Laravel is caching the view and put a TTL on it.
I know this isn't anything I am doing on my local web server because I have used other frameworks and I have never encountered this issue.
Upon searching the Internet, I can't find a great answer on how to disable this. I want to use Laravel, but find it worthless if it takes a while for my views to update each time I want to make a change. In fact, it sounds counter productive.
Is there any way to disable this? Why are my views taking forever to update right out of the box?
|
Laravel and view caching in development -- can't see changes right away
|
[Update] Redis Cluster was released in Redis 3.0.0 on 1 Apr 2015.
Redis cluster is currently in active development. See this article from Redis author: Antirez.
So I can pause other incremental improvements for a bit to focus on Redis Cluster. Basically my plan is to work mostly to cluster as long as it does not reach beta quality, and for beta quality I mean, something that brave users may put into production.
Redis Cluster will support up to ~1000 nodes.
The first release will have the following features (extracted from Antirez post):
Automatic partition of key space.
Hot resharding.
Only single key operations supported (and it will always be that way).
As of today antirez is working on the first Redis cluster client (redis-rb-cluster) in order to be used as a reference implementation.
I'll update this answer as soon as Redis Cluster goes production ready.
[Update] 03/28/2014 Redis Cluster is already used on large cluster in production (source: antirez tweets).
|
I was reading Redis documentation, and I am most interested in the partitioning feature.
Redis documentation states the following:
Data store or cache? Partitioning when using Redis ad a data store or
cache is conceptually the same, however there is a huge difference.
While when Redis is used as a data store you need to be sure that a
given key always maps to the same instance, when Redis is used as a
cache if a given node is unavailable it is not a big problem if we
start using a different node, altering the key-instance map as we wish
to improve the availability of the system (that is, the ability of the
system to reply to our queries). Consistent hashing implementations
are often able to switch to other nodes if the preferred node for a
given key is not available. Similarly if you add a new node, part of
the new keys will start to be stored on the new node. The main concept
here is the following: If Redis is used as a cache scaling up and down
using consistent hashing is easy. If Redis is used as a store, we need
to take the map between keys and nodes fixed, and a fixed number of
nodes. Otherwise we need a system that is able to rebalance keys
between nodes when we add or remove nodes, and currently only Redis
Cluster is able to do this, but Redis Cluster is not production ready.
From the last sentence I understand that Redis Cluster is not production ready. Does anyone knows whether this documentation is up to date, or Redis Cluster is already production ready?
|
Redis Cluster - production ready?
|
This is possible from FNH, in the example below see the 'Cache' property:
return Fluently.Configure(fileConfiguration)
.Database(MsSqlConfiguration
.MsSql2005
.ConnectionString(c => c.FromConnectionStringWithKey("Temp"))
.ShowSql()
.Cache(c => c.ProviderClass(typeof(NHibernate.Cache.HashtableCacheProvider).AssemblyQualifiedName)
.UseQueryCache()))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IMap>())
.ExposeConfiguration(c => {
c.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[] {new TestPostLoadListener()};
})
.BuildSessionFactory();
Cheers
AWC
Note, for Fluent NHibernate >= 3.4.0.0 it appears the configuration is slightly different. Use the nuget package for SysCache from http://nuget.org/packages/NHibernate.Caches.SysCache
return Fluently.Configure(fileConfiguration)
.Database(MsSqlConfiguration
.MsSql2005
.ConnectionString(c => c.FromConnectionStringWithKey("Temp"))
.ShowSql())
.Cache(c => c.ProviderClass<SysCacheProvider>().UseQueryCache())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IMap>())
.ExposeConfiguration(c => {
c.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[] {new TestPostLoadListener()};
})
.BuildSessionFactory();
|
Is ti possible to configure the L2 cache provider in code via FHN?
Adding a line to the following config is what I'm after:
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("Temp")).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IMap>())
.ExposeConfiguration(c => { })
.BuildSessionFactory();
Cheers
AWC
|
NHibernate L2 Cache configuration in Fluent NHibernate
|
See Caching Docker Images on Build #5358
for the answer(s). For Docker 1.12 available now on Travis, it is recommended to manually cache the images. For the Docker 1.13, you could use its --cache-from when it is on Travis.
Save:
before_cache:
# Save tagged docker images
- >
mkdir -p $HOME/docker && docker images -a --filter='dangling=false' --format '{{.Repository}}:{{.Tag}} {{.ID}}'
| xargs -n 2 -t sh -c 'test -e $HOME/docker/$1.tar.gz || docker save $0 | gzip -2 > $HOME/docker/$1.tar.gz'
Load:
before_install:
# Load cached docker images
- if [[ -d $HOME/docker ]]; then ls $HOME/docker/*.tar.gz | xargs -I {file} sh -c "zcat {file} | docker load"; fi
Also need to declare a cache folder:
cache:
bundler: true
directories:
- $HOME/docker
|
Is it possible to add a setting to cache my docker image anywhere in the travis configuration ? Mine is a bigger docker image and it takes a while for it to download.
Any suggestions ?
|
Can Travis CI cache docker images?
|
I found the answer to my question. That is the "shadow copy" folder for the .NET framework as specified in Windows Registry under HKCU\Software\Microsoft\Fusion\DownloadCacheLocation. Shadow copying is a feature in the .NET framework to allow assemblies used in an app domain to be updated without unloading the app domain. More about this feature in MSDN http://msdn.microsoft.com/en-us/library/ms404279.aspx.
The app domain where I was loading the assembly was configured to shadow copy files, by setting the ShadowCopyFiles property to true.
|
I have this assembly that for some reason Windows started to load from this path:
C:\Users\marius\AppData\Local\assembly\dl3\MP6PT6BV.2Z4\GMRQEZL9.LCB\46d762c5\8cf066ff_7eaecc01\X.DLL
That means whatever changes I do to the assembly, the new copy of it isn't loaded from its output folder but from that cached folder. I tried deleting the folder, even restarting Windows, it is generated again and the assembly loaded from there.
So, how can I get rid of it? What do I have to do to tell the system to load the DLL from its output folder and not from the cache?
|
what is cache AppData\Local\assembly\dl3?
|
The short answer is that it cannot be done securely.
There are, however, a lot of tricks that can be implemented to make it difficult for users to hit back and get sensitive data displayed.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
This will disable caching on client side, however this is not supported by all browsers.
If you have the option of using AJAX then sensitive data can be retrieved using a updatepanel that is updated from client code and therefore it will not be displayed when hitting back unless client is still logged in.
|
I have some website which requires a logon and shows sensitive information.
The person goes to the page, is prompted to log in, then gets to see the information.
The person logs out of the site, and is redirected back to the login page.
The person then can hit "back" and go right back to the page where the sensitive information is contained. Since the browser just thinks of it as rendered HTML, it shows it to them no problem.
Is there a way to prevent that information from being displayed when the person hits the "back" button from the logged out screen? I'm not trying to disable the back button itself, I'm just trying to keep the sensitive information from being displayed again because the person is not logged into the site anymore.
For the sake of argument, the above site/scenario is in ASP.NET with Forms Authentication (so when the user goes to the first page, which is the page they want, they're redirected to the logon page - in case that makes a difference).
|
Is there a way to keep a page from rendering once a person has logged out but hit the "back" button?
|
12
This is actually more tricky than it seems.
I assume you're using the angular translate module.
I did cache busting where it loads the json files:
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'AppScripts/i18n/{part}-{lang}.json' + '?cb=' + (new Date()).getTime()
});
That way it will never cache the language files, and will load the new ones on every request (without refreshing the page or clearing the cache).
The web config setting gets completely ignored, I believe because the way the plugin loads the files with ajax calls.
Also, the json files can't be minified with .net bundling because the keys will change when compressed, so instead of "MAIN.FIRSTNAME": "First Name" you'll have something like "abc": "First Name" and it won't work since the views have the original names.
You can also use the version if you keep one, to bust the cache only when you release a new version, something like
+ '?v=' + myVersionVar
instead of using current timestamp which will always load the files on every request.
Share
Improve this answer
Follow
answered Apr 19, 2017 at 15:07
AlxAlx
30133 silver badges1010 bronze badges
Add a comment
|
|
I'm running a single page app on IIS and using i18next library for translations in my app. The problem is that sometimes when I add new keywords to my translation.json file and hit refresh, the browser still uses the old cached translation file and this results in user seeing the added keywords but not translations. E.g. if I add a keyword "somekey": "Some text here..." then somekey would be displayed instead of the specified text.
As my translation.json file is located in a folder called locales like this:
locales
en
translation.json
I tried adding following setting to web.config:
<location path="locales">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
However, when I looked at the network traffic with Chrome developer tools, I noticed that translation.json file is still coming from cache and Cache-Control: no-cache header is missing. Why this does not work? What is right way to disable the caching of the file?
EDIT: Just checked the site again and it seems that translation.json file now has the Cache-Control: no-cache header and it is actually being retrieved from server every time I refresh the page. At this point I'm thinking that the issue might have had something to do with our release process and config changes not being applied. Not sure though.
|
How to disable caching for i18next translation.json files?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.