Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
You can use the global.asax appplication start method to initialize resources. Resources which will be used application wide basically. The following link should help you to find more information: http://www.asp.net/web-forms/tutorials/data-access/caching-data/caching-data-at-application-startup-cs Hint: If you use in process caching (which is usually the case if you cache something within the web context / thread), keep in mind that your web application is controlled by IIS. The standard IIS configuration will shut down your web application after 20 minutes if no user requests have to be served. This means, that any resources you have in memory, will be freed. After this happens, the next time a user accesses your web application, the global asax, application start will be excecuted again, because IIS reinitializes your web application. If you want to prevent this behaviour, you either configure the application pool idle timeout to not time out after 20minutes. Or you use a different cache strategy (persistent cache, distributed cache...). To configure IIS for this, here you can find more information: http://brad.kingsleyblog.com/IIS7-Application-Pool-Idle-Time-out-Settings/
I am writing an MVC webAPI that will be used to return values that will be bound to dropdown boxes or used as type-ahead textbox results on a website, and I want to cache values in memory so that I do not need to perform database requests every time the API is hit. I am going to use the MemoryCache class and I know I can populate the cache when the first request comes in but I don't want the first request to the API to be slower than others. My question is: Is there a way for me to automatically populate the cache when the WebAPI first starts? I see there is an "App_Start" folder, maybe I just throw something in here? After the initial population, I will probably run an hourly/daily request to update the cache as required. MemoryCache: http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx UDPATE Ela's answer below did the trick, basically I just needed to look at the abilities of Global.asax. Thanks for the quick help here, this has spun up a separate question for me about the pros/cons of different caching types. Pros/Cons of different ASP.NET Caching Options
Caching application data in memory: MVC Web API
While I don't believe there is any way to control the etags header behavior for GAE, this is caused by a bug in WebKit that causes all static content to be re-downloaded when receiving a 302 redirect after a POST request. Once WebKit fixes this bug, the issue should go away. If you must, you can temporarily work around this specific redirect-after-POST bug by redirecting via a Refresh header instead of using a 302 redirect. https://bugs.webkit.org/show_bug.cgi?id=38690 WebKit image reload on Post/Redirect/Get http://www.google.com/support/forum/p/Chrome/thread?tid=72bf3773f7e66d68&hl=en
Situation: running a Google App Engine site with my static content's default_expiration set to "14d" Problem: in Chrome and Safari, visiting a URL (not reloading, just putting the cursor in the address bar and hitting Enter), causes a ton of requests to be fired with If-None-Match headers. The responses are always 304 Not Modified, as expected. I can watch these requests get fired in a debugging proxy like Charles or Fiddler. Want: to avoid these requests and 304 responses entirely for static content -- simply trust the browser's cached content when it's available. We use the standard "cache static content for a really long time, we'll take care of appending ?version={version} modifications to our query strings when we need to bust the cache" system, so we'd really like to avoid the 304's. Belief: I think this is caused by the etag header that app engine sends down with every static content response. The app engine SDK does not send this header down, and I don't see this 304 behavior when messing around with the SDK. Any advice? Can you turn off etags for app engine's static content? Updated with an example piece of static content: http://www.khanacademy.org/stylesheets/shared-package/compressed.css
How can I get control of Google App Engine caching behavior in WebKit (etags gone crazy)?
This is because internally by default the pager loads a maximum of 3 pages (fragments) at the time: the one displaying, previous and next so if you have 5 fragments this will happen while you move from first to last: (where x is a loaded fragment) xx000 -> xxx00 -> 0xxx0 -> 00xxx -> 000xx Try using myPager.setOffscreenPageLimit(ITEMS_COUNT-1); This will tell the pager to keep all of them in memory and not destroy/create with every swipe (keep a close look on the memory management)
I'd like to cache a fragment view. My Activity has swipeable tabs and each tab calls a different fragment. But when i swipe between tabs the transition seems a quite slow because of the destruction of the fragment view, that is rebuilded during the swipe operation. Does anyone know how can i cache the view of each fragment to prevent this issue? I work with library support v4 and api 14 I tried to implement a constructor for the fragments, called by the activity container of the fragments: i call the constructor, the fragments are created as variable of the activity class and then, whenever a fragment has to show itself, the activity class returns the fragment object i created before, but this doesn't improve my application a lot because the view of the fragment is destroyed anyway
How to cache a fragment view
So if SQL Server has it's own cache, what is the benefit of an external Memcached (or similar) server? Yes SQL Server has its own cache but he caches only: - Query plans - pages from the database files but he does NOT cache: - results from a query e.g. you have a complex query which uses some aggregation on a lot of data ( think of: how many different countries we have in our customer database : SELECT DISTINCT Country from Customers GROUP BY country ) SQL Server will scan th WHOLE customer table, but your resultset will only a few entries long. When you reissue your query, SQL Server will reuse the query plan and will rescan the customer table, ( and if you are lucky the pages are still in memory ) When you use memcached you may store the few rows of your resultset and reuse them over and over again without connecting to the database server. So it takes some load from your database server. NOTE: Beware of some stale data, if your data changes on the SQL server !!
I've been reading a lot of articles that suggest putting a Memcached (or Velocity, etc) in front of a database is more efficient than hitting the database directly. It will reduce the number of hits on the database by looking up the data in a memory cache, which is faster than hitting the database. However, SQL Server has it's own memory cache for objects in the database. When data is retrieved, SQL Server maintains its cache and will (if necessary) pull the row from it's memory and not hit the disk. So if SQL Server has it's own cache, what is the benefit of an external Memcached (or similar) server? Most of the articles I have been reading are around social networking sites, that mostly use MySql. However, an article about MySpace, that uses SQL Server, suggests caching is used on that system as well. This article explains when caching should be used and this article is a counterpoint.
Memcached vs SQL Server cache
5 NPM has a global cache stored in ~/.npm Share Improve this answer Follow answered Jul 26, 2018 at 16:14 StevenSteven 5111 gold badge22 silver badges33 bronze badges 1 Some dependencies have postinstall steps which download binaries and may not use caching as you'd like (such as puppeteer, which downloads chrome every time). – justin.m.chase Dec 22, 2020 at 17:08 Add a comment  | 
We all know that downloading dependencies with npm can be very time consuming, specially when we are limited to old npm versions. For me, as a developer, this wasn't such a big deal because I had to do this very few times on my local development machine and everything worked with the node_modules cache in my project's folder. But now I want to take this the applications to a CI environment, with Jenkins. I realized a huge ammount of time was spent on downloading dependencies with npm. This is a problem because: npm downloads the dependencies in the project's folder, not a global folder such as Maven's /home/user/.m2 I have to clean up the Jenkins workspace folder in every run to avoid issues with the git checkout. I want a very elegant solution for caching the npm dependencies on my Jenkins slaves, but so far I can only think of: Removing everything but the node_modules folders from the Jenkins workspace. I don't like this because I could consume lots of HDD if I keep creating branches for my project. Each branch creates a workspace. doing something like cp ./node_modules /home/npm_cache after every npm install and then cp /home/npm_cache ./node_modules after the code checkout. I feel these solutions are terrible. There must be a better way to do this.
Cache NPM dependencies on Jenkins pipeline
If I understand your problem, I think I'd tackle it like this. It's a touch evil, but I think it's more reliable and on-point than the other solutions I see here. import inspect import functools import json def memoize_zeroadic_function_to_disk(memo_filename): def decorator(f): try: with open(memo_filename, 'r') as fp: cache = json.load(fp) except IOError: # file doesn't exist yet cache = {} source = inspect.getsource(f) @functools.wraps(f) def wrapper(): if source not in cache: cache[source] = f() with open(memo_filename, 'w') as fp: json.dump(cache, fp) return cache[source] return wrapper return decorator @memoize_zeroadic_function_to_disk(...SOME PATH HERE...) def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result
I have a python function that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result I modify time_consuming_function from time to time, but I would like to avoid having it run again while it's unchanged. [time_consuming_function only depends on functions that are immutable for the purposes considered here; i.e. it might have functions from Python libraries but not from other pieces of my code that I'd change.] The solution that suggests itself to me is to cache the output and also cache some "hash" of the function. If the hash changes, the function will have been modified, and we have to re-generate the output. Is this possible or ridiculous? Updated: based on the answers, it looks like what I want to do is to "memoize" time_consuming_function, except instead of (or in addition to) arguments passed into an invariant function, I want to account for a function that itself will change.
Hashing a python function to regenerate output when the function is modified
1 I ran into the exact same thing but solved it after noticing that I had inadvertently used [OutputCache] instead of [DonutOutputCache]! User error. Works in _Layout beautifully. Please double-check that you are using the proper [DonutOutputCache] attribute. Share Improve this answer Follow edited Feb 5, 2016 at 21:21 CodeNotFound 22.6k1010 gold badges6969 silver badges7171 bronze badges answered Feb 5, 2016 at 21:16 user61307user61307 19522 silver badges1414 bronze badges Add a comment  | 
In my ASP.NET MVC project, I have a login submenu in the navigation menu of my shared _Layout.cshtml file, displaying user info if the user is logged in, or signup/login options if not. The login submenu is a partial view in my shared folder named _LoginPartial: @using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { //display <ul> with user profile settings, omitted for brevity } else { //display <ul> to signup/login, omitted for brevity } While I heavily cache several actions of various controllers, I want to implement donut caching on _Layout so that _LoginPartial does not get cached, for obvious reasons. I'm using the mvcdonutcaching library to accomplish this (suggested in this answer) which provides some overloads of @Html.Action that have an additional bool excludeFromParentCache property. As such, I created a LayoutController with a UserAuth action which returns _LoginPartial: _LoginPartial0 ..And in my _LoginPartial1 file, where I want _LoginPartial2 to appear, I call the mvcdonutcaching _LoginPartial3 overload as such: _LoginPartial4 To test this, I have set an _LoginPartial5 with a long duration on the _LoginPartial6 action of my _LoginPartial7, but if I follow these steps: login navigate to /faq logout navigate to /faq /faq still shows me as logged in. What am I missing here? This is mvcdonutcaching's output in the actual HTML: _LoginPartial8 Update: I have also tried moving the menu in _LoginPartial9 to a partial view residing in the views of @using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { //display <ul> with user profile settings, omitted for brevity } else { //display <ul> to signup/login, omitted for brevity } 0 instead - the problem persists.
Donut caching _Layout with mvcdonutcaching ASP.NET MVC
They're both pretty solid projects. If you have pretty basic caching needs, either one of them will probably work as well as the other. You may also wish to consider doing the filtering in a database query if it's feasible. Often, using a tuned query that returns a smaller result set will give you better performance than loading 500,000 rows into memory and then filtering them.
Never used a cache like this before. The problem is that I want to load 500,000 + records out of a database and do some selecting/filtering wicked fast. I'm thinking about using a cache, and preliminarily found EHCache and OSCache, any opinions?
OSCache vs. EHCache
Firstly add the package (flutter_cache_manager) to pubspec.yaml file as following: dependencies: flutter: sdk: flutter flutter_cache_manager: ^1.1.3 After a day, I found the solution. Use the DefaultCacheManager object by calling emptyCache() method, this clears the cache data. DefaultCacheManager manager = new DefaultCacheManager(); manager.emptyCache(); //clears all data in cache.
i dont want to store image in cache.. iam using CachedNetworkImage for image loading.. I want know is there any option to remove or do not store image in cache like picasso.. my code: var annotatedImg = CachedNetworkImage( fit: BoxFit.fill, imageUrl: Constants.IMAGE_BASE_URL + widget._fileId + Constants.CONTOUR_IMG_SUFFIX, placeholder: (context, url) => progressBar, errorWidget: (context, url, error) => new Icon(Icons.error), ); i have tried annotatedImg.cacheManager.emptyCache(); but its shows cant call emptyCache is null..
how to clear cache in CachedNetworkImage flutter
No, that's not the correct way. Here is the correct way: response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. You'll probably see someone else suggesting other entries/attributes, but those are completely irrelevant when at least the above are mentioned. Don't forget to clear your browser cache before testing after the change. See also: Caching tutorial for webmasters Making sure a page is not cached across all browsers
I want to ensure that my servet's response is never cached by the broswer, such that even if two identical requests are made (a nanosecond apart), the server is always contacted. Is this the correct way to achieve this: class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); } } Thanks, Don
HTTP response caching
You don't say what sort of objects you're looking to store, so it's a little difficult to offer detailed advice. However some (not exclusive) approaches, in no particular order, are: Use a flyweight pattern wherever possible. Caching to disc. There are numerous cache solutions for Java. There is some debate as to whether String.intern is a good idea. See here for a question re. String.intern(), and the amount of debate around its suitability. Make use of soft or weak references to store data that you can recreate/reload on demand. See here for how to use soft references with caching techniques. Knowing more about the internals and lifetime of the objects you're storing would result in a more detailed answer.
How do you optimize the heap size usage of an application that has a lot (millions) of long-lived objects? (big cache, loading lots of records from a db) Use the right data type Avoid java.lang.String to represent other data types Avoid duplicated objects Use enums if the values are known in advance Use object pools String.intern() (good idea?) Load/keep only the objects you need I am looking for general programming or Java specific answers. No funky compiler switch. Edit: Optimize the memory representation of a POJO that can appear millions of times in the heap. Use cases Load a huge csv file in memory (converted into POJOs) Use hibernate to retrieve million of records from a database Resume of answers: Use flyweight pattern Copy on write Instead of loading 10M objects with 3 properties, is it more efficient to have 3 arrays (or other data structure) of size 10M? (Could be a pain to manipulate data but if you are really short on memory...)
How do you make your Java application memory efficient?
There is no way to do that using Cache facade. Its interface represents the functionality that all underlying storages offer and some of the stores do not allow listing all keys. If you're using the FileCache, you could try to achieve that by interacting with the underlying storage directly. It doesn't offer the method you need, so you'll need to iterate through the cache directory. It won't be too efficient due to a lot of disk I/O that might need to happen. In order to access the storage, you need to do $storage = Cache::getStore(); // will return instance of FileStore $filesystem = $storage->getFilesystem(); // will return instance of Filesystem $keys = []; foreach ($filesystem->allFiles('') as $file1) { foreach ($filesystem->allFiles($file1) as $file2) { $keys = array_merge($keys, $filesystem->allFiles($file1 . '/' . $file2)); } }
The Cache class in laravel has methods such as get('itemKey') to retrieve items from the cache, and remember('itemKey', ['myData1', 'myData2']) to save items in the cache. There is also a method to check if an item exists in the cache: Cache::has('myKey'); Is there any way, (when using the file-based cache driver), to get a list of all items in the cache? For instance, something that might be named something like "Cache::all()" that would return: [ 'itemKey' => [ 'myData1', 'myData2' ], 'myKey' => 'foo' ] The only way I can think of doing this is to loop through all possible key names using the Cache::has() method. i.e. aaa, aab, aac, aad... but of course, this is not a solution. I can't see anything in the documentation or the API that describes a function like this, but I don't think its unreasonable to believe that one must exist.
How to get list of all cached items by key in Laravel 5?
This is already answered here. Pasting code snippet from the link for your reference. myModule.config(['$httpProvider', function($httpProvider) { //initialize get if not there if (!$httpProvider.defaults.headers.get) { $httpProvider.defaults.headers.get = {}; } // Answer edited to include suggestions from comments // because previous version of code introduced browser-related errors //disable IE ajax request caching $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT'; // extra $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache'; $httpProvider.defaults.headers.get['Pragma'] = 'no-cache'; }]);
I'm trying to disable the cache in my AngularJS app, but it isn't working with the following code: $http.get("myurl",{cache:false}) When I use "myurl&random="+Math.random(), the cache is disabled; but, I'd like a different approach.
Disabling AngularJS $http cache
You can take look at about:networking#dns which directly lets you clear the cache. And Where does Firefox keep cached DNS responses? had already been answered by Firefox's Support Team. ScreenShot: By the way for chrome it is chrome://net-internals/#dns
Like in the title, how to clear that cache? There are some plugins, but its installation is disabled for Firefox Quantum... https://addons.mozilla.org/en-US/firefox/addon/dns-flusher/ https://addons.mozilla.org/en-us/firefox/addon/clear-dns-cache/
How to clear DNS cache in Firefox Quantum?
Figured it out, to target a specific file (in this case index.php), add this code to the bottom of .htaccess <Files index.php> FileETag None Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" </Files> Alternatively to target a specific selection of files, ie. I'd like to cache images but nothing else (files that match html, htm, js, css, php will not be cached): <filesMatch "\.(html|htm|js|css|php)$"> FileETag None Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" </filesMatch> To check the .htaccess was being read I entered a few lines of rubbish at the bottom, found out it wasn't being read, renamed it from htaccess to .htaccess and it worked.
I have a page on a site which uses random() twig, in Firefox and Chrome it is prevented from working because it gets cached as soon as the page loads. Is there a way to turn off caching of a particular file via the Apache configs, lets call it default.html or even better just turn off caching for the script part of that file but keep caching image files? I have tried .htaccess but this does not work. The only way currently that allows the script to work is to turn off caching globally via PHP headers: <?php header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: post-check=0, pre-check=0', FALSE); header('Pragma: no-cache'); ?> But as I only need to turn off caching for an individual page, turning it off for everything seems crazy.
Turn OFF Cache for specific file with Apache
I don't think it works that way. You'll have to specify all of the images one by one, or have a simple PHP script to loop through the directory and output the file (with the correct text/cache-manifest header of course).
I have a lot of images in a folder that are used in the application. When using the cache manifest it would be easier maintenance wise if I could specify a wild card to load all the images or files in a certain directory to be cached. E.g. CACHE MANIFEST # 2011-11-3-v0.1.8 #-------------------------------- # Pages #-------------------------------- ../index.html ../edit.html #-------------------------------- # JavaScript #-------------------------------- ../js/jquery.js ../js/main.js #-------------------------------- # Images #-------------------------------- ../img/*.png Can this be done? Have tried it in a few browsers with ../img/* as well but it doesn't seem to work.
How do I specify a wildcard in the HTML5 cache manifest to load all images in a directory?
41 put below code in your wp-config.php file. define('WP_CACHE', false); Share Improve this answer Follow answered Sep 13, 2017 at 11:20 Akshay ShahAkshay Shah 3,40622 gold badges2020 silver badges3434 bronze badges 8 3 setting this flag still results in transients. – Kraang Prime Mar 25, 2018 at 10:24 Are you using any plugin? – Akshay Shah Mar 25, 2018 at 10:34 Yes. WooCommerce. This version doesn't seem to have any way to turn off using transients. – Kraang Prime Mar 25, 2018 at 14:19 I do not think so this is the woocommerce issue. – Akshay Shah Mar 25, 2018 at 14:41 Looking at wordpress documentation, there doesn't appear to be a way to disable transients. ( google comes up with results on how to clear them, but not to prevent them in the first place ). Transients are a form of 'cache' stored in wp_options table. – Kraang Prime Mar 25, 2018 at 15:17  |  Show 3 more comments
I am creating a website, but I needed to do refresh several time to see the changes I made in website. Is there any option that I can use to disable cache in WordPress?
How to disable cache in wordpress
I'm using MemoryCache to store query results, and it's working fine so far. Here are a few links that I've used to implement it. - Using MemoryCache in .NET 4.0 (codeproject) - Using MemoryCache in .NET 4.0 (blog entry) As I read them now, I find them not that clear, so maybe there is a better link that I've lost somewhere. Here is a sample of my code which I hope is clear enough so that you see how it works public static class AgencyCacheManager { private static MemoryCache _cache = MemoryCache.Default; public static List<RefAgency> ListAgency { get { if (!_cache.Contains("ListAgency")) RefreshListAgency(); return _cache.Get("ListAgency") as List<Agency>; } } public static void RefreshListAgency() { var listAgency = GetAllComplete(); CacheItemPolicy cacheItemPolicy = new CacheItemPolicy(); cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddDays(1); _cache.Add("ListAgency", listAgency, cacheItemPolicy); } } And to retrieve the list from cache public Agency FindBy(string agencyId) { return AgencyCacheManager.ListAgency.SingleOrDefault(x => x.AgencyPartnerCode == agencyId); }
I am working on mvc4 web application. I want to cache some database queries results and views on server side. I used- HttpRuntime.Cache.Insert() but it caches the data on client side. Please help.
How to cache data on server in asp.net mvc 4?
What are the resources that are being cached? I suspect js/css files, a good way to handle this is to add a query param with a version to the path of those resources in order to force the browser to load the new file if the version changed, something like this: <script type="text/javascript" src="your/js/path/file.js?v=1"></script> <link href="/css/main.css?v=1" media="screen,print" rel="stylesheet" type="text/css"> And when you release a new update of your website, replace the version as follows: <script type="text/javascript" src="your/js/path/file.js?v=2"></script> <link href="/css/main.css?v=2" media="screen,print" rel="stylesheet" type="text/css"> The browser will thing that the file is a new file and it will update the cache. Hope this helps. In order to disable html caching, you can add a metatag to your file as follows: <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> But this will entirely disable caching of html files that have this metatag, I don't think there is a way to handle this as easily as with js/css files, you can set the metatag to refresh the html in a future date though. Here is an article describing how to use that metatag if you need more info: http://www.metatags.info/meta_http_equiv_cache_control
I am making a website and am running into an issue with website cache for my users. I develop my website and have set chrome developer tools to disable cache for my website for development. The issue is when i release a new change to prod all my users don't get the update because of their browser cache. When i delete the cache for my website manually on a friends computer it works but i obviously cant expect everyone to do this to get the new updates. Is there anyway for me to get around this with versioning or something? i have looked around but cant seem to find anything. edit: i know i can prevent caching at all but i don't want to completely prevent caching that seems like a bad design
Website html doesnt update for users because of cache
In general it is a bad idea to share overlapping memory regions like if one thread processes 0,2,4... and the other processes 1,3,5... Although some architectures may support this, most architectures will not, and you probably can not specify on which machines your code will run on. Also the OS is free to assign your code to any core it likes (a single one, two on the same physical processor, or two cores on separate processors). Also each CPU usually has a separate first level cache, even if its on the same processor. In most situations 0,2,4.../1,3,5... will slow down performance extremely up to possibly being slower than a single CPU. Herb Sutters "Eliminate False Sharing" demonstrates this very well. Using the scheme [...n/2-1] and [n/2...n] will scale much better on most systems. It even may lead to super linear performance as the cache size of all CPUs in sum can be possibly used. The number of threads used should be always configurable and should default to the number of processor cores found.
I am implementing an image filtering operation in C using multiple threads and making it as optimized as possible. I have one question though: If a memory is accessed by thread-0, and concurrently if the same memory is accessed by thread-1, will it get it from the cache ? This question stems from the possibility that these two threads could be running into two different cores of the CPU. So another way of putting this is: do all the cores share the same common cache memory ? Suppose i have a memory layout like the following int output[100]; Assume there are 2 CPU cores and hence I spawn two threads to work concurrently. One scheme could be to divide the memory into two chunks, 0-49 and 50-99 and let each thread work on each chunk. Another way could be to let thread-0 work on even indices, like 0 2 4 and so on.. while the other thread work on odd indices like 1 3 5 .... This later technique is easier to implement (specially for 3D data) but I am not sure if I could use the cache efficiently this way.
Multiple threads and CPU cache
Operating system does in memory caching by default. It's called page cache. In addition, you can enable sendfile to avoid copying data between kernel space and user space.
I have Nginx running in a Docker container, and it serves some static files. The files will never change at runtime - if they actually do change, the container will be stopped, the image will be rebuilt, and a new container will be started. So, to improve performance, it would be perfect if Nginx would read the static files only one single time from disk and then server it from memory forever. I have found some configuration options to configure caching, but at least from what I have seen none of them provided this "forever" behavior that I'm looking for. Is this possible at all? If so, how do I need to configure Nginx to achieve this?
Cache a static file in memory forever on Nginx?
First, a list of opcode cachers for php. Second Memcache/MemcacheD is not an Opcode Cacher. It is a distributed memory caching system. It does not improve the speed/performance of your PHP code. It can be used to store data only. APC, EAccelerator, XCache and the others are non distributed, meaning you can only store data on the local web-server. However all of these are opcode cachers and can improve the performance of your PHP app. Most, excluding EAccelerator (in the current version) can also store data. I generally choose APC for the opcode cacher (It reportedly will be included into the core of PHP 6). However if I also have more than one web-server for the site I will also make use of MemcacheD. Edit 1 I agree it is very annoying to setup APC, Memcache on MAMP. There are however tutorials out there dealing with such. Edit 2 Also with regards to the best Opcode Cacher for your app really depends on which server you are using. Some work better on some systems. It also depends on the size and scale of your app as to how the cachers perform. Edit 3 Very interesting article here about comparing performance of a few different cachers. (This article appears to be written in 2006 and should not really be used for current reference)
At work, we've recently started designing an application to me "large scale" (we're engineering for the potential to serve up many millions of hits a day). One of the senior devs and the sysadmin have set up memcache on the server. As I understand it, Memcache will hold query results and certain tables in memory for X amount of time and keep everything hunky dory. A drawback of memcache it seems is that I just can't for the life of me manage to set it up on my local dev environment. I've followed a few different instructionals on how to compile it for yourself. Most, if not all of the steps seem to work properly but get this error on PHPLoad: [11-Sep-2010 16:02:30] PHP Warning: PHP Startup: Unable to load dynamic library '/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcached.so' - dlopen(/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcached.so, 9): image not found in Unknown on line 0 Not the primary question but incedentally, if you've been able to compile Memcache for MAMP 1.9 on Snow Leopard, please let me know the trick. My primary question is about what the differences are between the various web caching technologies. I've seen mention of Memcache, APC and Xcache (here: Cache results of a mysql query manually to a txt file) but don't know the pros, cons and differences between each. To my mind, Memcache has the advantage of being the one that the project's lead dev and our sysadmin chose. It has the disadvantage of being utter foobar to try and set up and compile on a Mac. :-^) Anyone who I'd love to hear from anyone who can enumerate the pros and cons of each (or even one of) the other cachine technologies. Where are they best used, how are they best used. And so on. It's all useful information I think. Thanks so much for lending your time to expanding my knowledge. - Alex.
Difference between Memcache, APC, XCache and other alternatives I've not heard of
18 The browser ignores the Expires header if you refresh the page. It always checks whether the cache entry is still valid by contacting the web server. Ideally, it will use the If-Modified-Since request header so that the server can return '304 Not modified' if the cache entry is still valid. You're not setting the Last-Modified header, so the browser has to perform an unconditional GET of the content to ensure that it is up to date. Some rules of thumb for setting Expires and Last-Modified are described in this blog post: http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/ Share Improve this answer Follow answered Jun 26, 2009 at 12:37 HttpWatchSupportHttpWatchSupport 2,81411 gold badge1717 silver badges1616 bronze badges 1 6 "The browser ignores the Expires header if you refresh the page." Thank you! I did not know this. – Noah Sussman Jun 14, 2012 at 18:19 Add a comment  | 
I have a situation where my (embedded) web server is sending Expires header, but the browser does not seem to respect the header setting, i.e., if I refresh the page, the browser requests the resources that are supposed to be cached. Following are the headers that are getting exchanged: https://192.168.1.180/scgi-bin/ajax/ajax.cgi GET /scgi-bin/ajax/ajax.cgi HTTP/1.1 Host: 192.168.1.180 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 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 Keep-Alive: 300 Connection: keep-alive Cache-Control: max-age=0 HTTP/1.x 200 OK Date: Wed, 24 Jun 2009 20:26:47 GMT Server: Embedded HTTP Server. Connection: close Content-Type: text/html ---------------------------------------------------------- https://192.168.1.180/scgi-bin/ajax/static.cgi?fn=images/logo.jpg&ts=20090624201057 GET /scgi-bin/ajax/static.cgi?fn=images/logo.jpg&ts=20090624201057 HTTP/1.1 Host: 192.168.1.180 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729) 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 Keep-Alive: 300 Connection: keep-alive Referer: https://192.168.1.180/scgi-bin/ajax/ajax.cgi Cache-Control: max-age=0 HTTP/1.x 200 OK Date: Wed, 24 Jun 2009 20:26:47 GMT Server: Embedded HTTP Server. Connection: close Expires: Wed, 1 Jun 2011 20:00:00 GMT Content-Type: image/jpg ---------------------------------------------------------- The ajax.cgi returns an html page with a logo graphic (via the static.cgi script), which I'd like cached, but the browser is asking for the logo on every refresh.
HTTP Expires header not respected by browser?
19 This is working in ASP.NET Core 2.2 to 3.1: I know this is a bit similar to Fredrik's answer but you don't have to type literal strings in order to get the cache control header app.UseStaticFiles(new StaticFileOptions() { HttpsCompression = Microsoft.AspNetCore.Http.Features.HttpsCompressionMode.Compress, OnPrepareResponse = (context) => { var headers = context.Context.Response.GetTypedHeaders(); headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromDays(30) }; } }); Share Improve this answer Follow edited Jan 12, 2021 at 18:43 JHBonarius 11k33 gold badges2424 silver badges4646 bronze badges answered Mar 13, 2020 at 18:36 HMZHMZ 3,00911 gold badge2020 silver badges3232 bronze badges 3 you are missing Expires header. – Ali Jul 8, 2020 at 7:29 3 @Ali If a response contains both the Expires header and the max-age directive, max-age takes precedence. Reference: 13.2.4 Expiration Calculations - w3.org/Protocols/rfc2616/rfc2616-sec13.html The max-age directive takes priority over Expires, so if max-age is present in a response, the calculation is simply: – webStuff Nov 6, 2020 at 1:18 5 Note: it is not required to set the HttpsCompressionMode! – JHBonarius Jan 12, 2021 at 18:43 Add a comment  | 
I can't seem to enable caching of static files in ASP.NET Core 2.2. I have the following in my Configure: public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseCors(...); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseSignalR(routes => { routes.MapHub<NotifyHub>("/..."); }); app.UseResponseCompression(); app.UseStaticFiles(); app.UseSpaStaticFiles(new StaticFileOptions() { OnPrepareResponse = (ctx) => { ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=31557600"; // cache for 1 year } }); app.UseMvc(); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseVueCli(npmScript: "serve", port: 8080); } }); } When I try and Audit the production site on HTTPS using chrome I keep getting "Serve static assets with an efficient cache policy": In the network tab there is no mention of caching in the headers, when I press F5 it seems everything is served from disk cache. But, how can I be sure my caching setting is working if the audit is showing its not?
How to cache static files in ASP.NET Core?
Intel uses MESIF protocol (http://www.realworldtech.com/common-system-interface/5/, https://en.wikipedia.org/wiki/MESIF_protocol) in QuickPath and AMD uses MOESI protocol (https://en.wikipedia.org/wiki/MOESI_protocol, http://www.m5sim.org/MOESI_hammer) with or without Probe Filter in HyperTransport. But these protocols are for inter-chip communication (a AMD bulldozer socket has 2 chips in MCM). As far as I know, in both processors intra-chip coherence is made at L3 cache. A tool you could use to check for NUMA performance issues is numagrind: http://dx.doi.org/10.1109/IPDPS.2011.100
For my bachelor thesis I have to analyse the effecs of False Sharing on multicore systems. So looking for the different cache-coherence-protocol-types I have come across on Wikipedia that Intel has developed the MESIF cache-coherence-protocol, but there is no information that Intel also uses this. Looking at the manual Intel® 64 and IA-32 Architectures Developer's Manual: Vol. 3A I couldn't find anything about MESIF but the MESI-protocol. So the question is, doesn't Intel use its own cache-coherence-protocol. Or am I searching it in the wrong document.
Which cache-coherence-protocol does Intel and AMD use?
9 Introduction Here is my note, for some other guy who running in to this problem, I think this is should be in the docs. By default, redis gives you 16 separate databases, but laravel out of the box will try to use database 0 for both sessions and cache. Our solution is to let Redis caching using database 0, and database 1 for Session, there for solving the session clear by running php artisan cache:clear problem. Note: Tested at Laravel 5.1 1. Setting up Session Redis connection Modify config/database.php, add session key to the redis option: 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], 'session' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 1, ], ], 2. Make use of the session connection Modify config/session.php, change the following: 'connection' => null, to: 'connection' => 'session', 3. Using Redis as session driver Modify .env, change config/database.php0: config/database.php1 4. Testing out Execute the following artisan command, then check your login state: config/database.php2 If the login state persists, voilà! Share Improve this answer Follow answered Jul 30, 2016 at 10:59 CharlieJadeCharlieJade 1,1731414 silver badges1010 bronze badges 0 Add a comment  | 
I want to put session and cache data into redis. This is my configuration in database.php: 'redis' => array( 'cluster' => false, 'default' => array( 'host' => '192.168.56.101', 'port' => 6379, 'database' => 0, ), 'session' => array( 'host' => '192.168.56.101', 'port' => 6379, 'database' => 1, ), ), session.php: return array( 'driver' => 'redis', 'connection' => 'session', ); cache.php: 'driver' => 'redis', However, where I write code like this: Cache::remember('aa',1,function(){ return 'bb'; }); cache driver uses the same redis database as session driver does, which results in: 127.0.0.1:6379[1]> keys * 1) "aa" 2) "e0606244bec40b0352fb2b7b65d98049e49f6189" Anyone knows how to force cache to use a specific redis connection? Or I have to mix them up together?
Laravel: how to separate cache and session into different redis database?
You can implement both schemes cache expiration by using CacheEntryChangeMonitor. Insert a cache item without information with absolute expiration, then create a empty monitorChange with this item and link it with a second cache item, where you will actually save a slidingTimeOut information. object data = new object(); string key = "UniqueIDOfDataObject"; //Insert empty cache item with absolute timeout string[] absKey = { "Absolute" + key }; MemoryCache.Default.Add("Absolute" + key, new object(), DateTimeOffset.Now.AddMinutes(10)); //Create a CacheEntryChangeMonitor link to absolute timeout cache item CacheEntryChangeMonitor monitor = MemoryCache.Default.CreateCacheEntryChangeMonitor(absKey); //Insert data cache item with sliding timeout using changeMonitors CacheItemPolicy itemPolicy = new CacheItemPolicy(); itemPolicy.ChangeMonitors.Add(monitor); itemPolicy.SlidingExpiration = new TimeSpan(0, 60, 0); MemoryCache.Default.Add(key, data, itemPolicy, null);
I want to use System.Runtime.Caching.MemoryCache for caching some of my objects. I want to be sure that the object is refreshed once a day (absolute expiration) but I also want to make it expire if it hasn't been used in the last hour (sliding expiration). I try to do: object item = "someitem"; var cache = MemoryCache.Default; var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddDays(1); policy.SlidingExpiration = TimeSpan.FromHours(1); cache.Add("somekey", item, policy); But I'm getting an error: "ArgumentException" with "AbsoluteExpiration must be DateTimeOffset.MaxValue or SlidingExpiration must be TimeSpan.Zero."
Combine Sliding and Absolute Expiration
Hope following link may be helpful to you... A sample application. Also have a look on Spring's documentation for cache abstraction and spring source blog post.
I am new to spring annotation and i want to create a sample example which shows the use of @Cacheable annotation in spring 3.1 does any one have guidance to create this ?
spring 3.1 @Cacheable example
You can't do anything about it. You can't control what headers google server sends. I would even go so far as to say it is reporting a false positive that you should fix. http://redbot.org/?uri=http%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DOpen%2BSans%3A400%2C800 As you can see the resource is cached, has a max age header and is even compressed. You site is fast enough! I wouldn't worry about getting 100. You can probably stop optimizing it. But if you want to tinker some more, here's a few ideas on improving things, I ran a report: http://www.webpagetest.org/result/130703_H7_15KM/ I would have your server send a 204 No Content header for your non-existent favicon.ico file OR make one and add it so there's no 404 on the resource. Use a CDN for your resources Use progressive jpegs and optimize the ones you're using
So I'm creating an ultra optimized site, and my page load speed with https://developers.google.com/speed/pagespeed/ is 99 (out of 100). The only thing keeping me away from full hundred is this: By specifying a cache validator - a Last-Modified or ETag header - you ensure that the validity of cached resources can efficiently be determined. What?! I don't know what should I do. How do I set a cache validator for google webfonts? I've the webfont like this: <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800' rel='stylesheet' type='text/css'>. I'm on ubuntu with apache2 if that matters. Downloading the webfont to server and using it from there drops the score to 96 so that won't help either.
Cache validator for Google Webfonts
Try LiteSQL and Hiberlite and see if they can be of use to you.
Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers. We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations. Closed 8 years ago. Improve this question I am looking for database-caching framework for C++ providing the following: Generate object/table representations via some pseudo-language (macros/templates) Retrieve objects from DB by key when needed LRU caching Immediate and delayed update of DB on object update (via getter/setter methods)
Hibernate-like framework for C++ [closed]
What gives? Is there an up-to-date replacement provider that I can use? They have been deprecated in favor of the classes implementing the new Hibernate 3.3/3.5 SPI with its CacheRegionFactory. These implementations are respectively: net.sf.ehcache.hibernate.EhCacheRegionFactory net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory Benefits of the new SPI include: The SPI removed synchronization in the Hibernate cache plumbing. It is left up to the caching implementation on how to control concurrent access. Ehcache, starting with 1.6, removed syncrhonization in favour of a CAS approach. The results, for heavy workloads are impressive. The new SPI provides finer grained control over cache region storage and cache strategies. Ehcache 2.0 takes advantage of this to reduce memory use. It provides read only, nonstrict read write and read write strategies, all cluster safe. Ehcache 2.0 is readily distributable with Terracotta Server Array. This gives you cluster safe operation (coherency), HA and scale beyond the limits of an in-process cache, which is how most Hibernate users use Ehcache today. There is the existing ehcache.jar and ehcache-terracotta.jar which provides the client library. (...) You are thus encouraged to use the new implementations. Configuration is done via the following property: <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory </property> That replaces the hibernate.cache.provider_class property. References Hibernate Blog Ehcache 2.0 supports new Hibernate 3.3 caching provider EhCache documentation Upgrading From Ehcache versions prior to 2.0 Hibernate Second Level Cache
I am configuring my hibernate project to use a 2nd-level cache provider, so that I can take advantage of query caching. I added a dependency to ehcache: <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.2.0</version> </dependency> I think that the provider class I want to use is: net.sf.ehcache.hibernateEhCacheProvider When I look at the referenced libraries in eclipse, I see the @Deprecated annotation on EhCacheProvider, and also on SingletonEhCacheProvider. What gives? Is there an up-to-date replacement provider that I can use? I am using hibernate version 3.4.0.GA, in case it matters.
Why is EhCacheProvider deprecated?
Yes, you can specify using a Spring-EL expression along these lines: @Override @Cacheable(key="#bar.name.concat('-').concat(#bar.id)") public int foo(Bar bar) { .... } or define a modified hashCode on bar and call that: @Override @Cacheable(key="#bar.hashCodeWithIdName") public int foo(Bar bar) { .... }
I have a service that takes in a DTO and returns some result: @Override public int foo(Bar bar) { .... } Bar is as follows (simplified): public class Bar { public int id; public String name; public String baz; @Override public int hashCode() { //this is already being defined for something else ... } @Override public boolean equals(Object o) { //this is already being defined for something else ... } } I want to use @Cacheable on the foo method; however, I want to hash on the id and name properties, but not baz. Is there a way to do this?
@Caching With Multiple Keys
You could wrap each of your cached items in a WeakReference. This would allow the GC to reclaim items if-and-when required, however it doesn't give you any granular control of when items will disappear from the cache, or allow you to implement explicit expiration policies etc. (Ha! I just noticed that the example given on the MSDN page is a simple caching class.)
I have some places where implementing some sort of cache might be useful. For example in cases of doing resource lookups based on custom strings, finding names of properties using reflection, or to have only one PropertyChangedEventArgs per property name. A simple example of the last one: public static class Cache { private static Dictionary<string, PropertyChangedEventArgs> cache; static Cache() { cache = new Dictionary<string, PropertyChangedEventArgs>(); } public static PropertyChangedEventArgs GetPropertyChangedEventArgs( string propertyName) { if (cache.ContainsKey(propertyName)) return cache[propertyName]; return cache[propertyName] = new PropertyChangedEventArgs(propertyName); } } But, will this work well? For example if we had a whole load of different propertyNames, that would mean we would end up with a huge cache sitting there never being garbage collected or anything. I'm imagining if what is cached are larger values and if the application is a long-running one, this might end up as kind of a problem... or what do you think? How should a good cache be implemented? Is this one good enough for most purposes? Any examples of some nice cache implementations that are not too hard to understand or way too complex to implement?
C#: How to implement a smart cache
I tried to lure better answers by offering 100 points as a bounty, but none of the answers were really satisfying. I would aggregate the recommended solutions like this: Using APC as a session storage APC cannot really be used as a session store, because there is no mechanism available to APC that allows proper locking, But this locking is essential to ensure nobody alters the initially read session data before writing it back. Bottom line: Avoid it, it won't work. Alternatives A number of session handlers might be available. Check the output of phpinfo() at the Session section for "Registered save handlers". File storage on RAM disk Works out-of-the-box, but needs a file system mounted as RAM disk for obvious reasons. Shared memory (mm) Is available when PHP is compiled with mm enabled. This is builtin on windows. Memcache(d) PHP comes with a dedicated session save handler for this. Requires installed memcache server and PHP client. Depending on which of the two memcache extensions is installed, the save handler is either called memcache or memcached.
Storing sessions in disk very slow and painful for me. I'm having very high traffic. I want to store session in Advanced PHP Cache, how can I do this?
How to store PHP sessions in APC Cache?
We append a product build number to the end of all Javascript (and CSS etc.) like so: <script src="MyScript.js?4.0.8243"> Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload. This has the additional benefit that you can set HTTP headers that mean "never cache!"
I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version. Not until I force the browser to clear the cache do I see the changes. Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the Google Web Toolkit where they actually create a new JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names. Is there a list of best practices somewhere?
Aggressive JavaScript caching
33 In the case that the page is found in the TLB (TLB hit) the total time would be the time of search in the TLB plus the time to access memory, so TLB_hit_time := TLB_search_time + memory_access_time In the case that the page is not found in the TLB (TLB miss) the total time would be the time to search the TLB (you don't find anything, but searched nontheless) plus the time to access memory to get the page table and frame, plus the time to access memory to get the data, so TLB_miss_time := TLB_search_time + memory_access_time + memory_access_time But this is in individual cases, when you want to know an average measure of the TLB performance, you use the Effective Access Time, that is the weighted average of the previous measures EAT := TLB_miss_time * (1- hit_ratio) + TLB_hit_time * hit_ratio or EAT := (TLB_search_time + 2*memory_access_time) * (1- hit_ratio) + (TLB_search_time + memory_access_time) * hit_ratio Share Improve this answer Follow edited Jul 1, 2015 at 0:55 answered Jul 1, 2015 at 0:43 SantiagoSantiago 52255 silver badges1212 bronze badges 2 If it was a 3 level paging system, would TLB_hit_time be equal to: TLB_search_time + 3* memory_access_time and TLB_miss_time be TLB_search_time + 3*(memory_access_time + memory_access_time) and EAT would then be the same? – qwerty Apr 27, 2016 at 18:36 @qwerty yes, EAT would be the same. In your example the memory_access_time is going to be 3* always, because you always have to go through 3 levels of pages, so EAT is independent of the paging system used – Santiago May 19, 2016 at 3:39 Add a comment  | 
This is a paragraph from Operating System Concepts, 9th edition by Silberschatz et al: The percentage of times that the page number of interest is found in the TLB is called the hit ratio. An 80-percent hit ratio, for example, means that we find the desired page number in the TLB 80 percent of the time. If it takes 100 nanoseconds to access memory, then a mapped-memory access takes 100 nanoseconds when the page number is in the TLB. If we fail to find the page number in the TLB then we must first access memory for the page table and frame number (100 nanoseconds) and then access the desired byte in memory (100 nanoseconds), for a total of 200 nanoseconds. (We are assuming that a page-table lookup takes only one memory access, but it can take more, as we shall see.) To find the effective memory-access time, we weight the case by its probability: effective access time = 0.80 × 100 + 0.20 × 200 = 120 nanoseconds but in the 8th edition of the same book I'm confused with the effective access time Can someone explain it for me?
calculate the effective access time
You have to also specify the templates module as a dependency of your module. For example: angular.module('myApp', ['templates', 'ngDialog']) Hope this helps.
I have a project using gulp and angular. I want to click a button and a pop up containing the html to show. In the build.js file i have the following code: gulp.task('templates', function() { gulp.src(['!./apps/' + app + '/index.html', './apps/' + app + '/**/*.html']) .pipe(plugins.angularTemplatecache('templates.js', { standalone: true, module: 'templates' })) .pipe(gulp.dest(buildDir + '/js')); }); in my app.js file i have: .controller('PopupCtrl', function($scope, ngDialog) { $scope.clickToOpen = function () { ngDialog.open({ template: 'templates/popup.html' }); }; }) I get an error on clicking the button: GET http://mylocalhost:3000/templates/popup.html 404 (Not Found) My templates.js file contains: angular.module("templates", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/popup.html", "my html") ...etc Why does the template cache not recognise the call to templates/popup.html and show what is in the cache rather than looking at the 404'd URL? Just to say what I have tried, I manually copied the template file into the directory it was looking and it found it. This is not the solution though as I want it taken from cache. Thanks
Angular Template cache not working
The -initWithContentsOfFile: creates a new image without caching, it's an ordinary initialization method. The +imageNamed: method uses cache. Here's a documentation from UIImage Reference: This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object. UIImage will retain loaded image, keeping it alive until low memory condition will cause the cache to be purged. Update for Swift: In Swift the UIImage(named: "...") function is the one that caches the image.
UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"xx.jpg"] UIImage *img = [UIImage imageNamed:@"xx.jpg"] In the second type will the image get cached ? Whereas the in the first type the images doesn't get cached?
Does the UIImage Cache image?
Don't try to avoid 301 caching. If you don't want any user agent to cache your redirect, then simply don't use a 301 redirect. In other words, 301 caching is here to stay, and semantically, it's a permanent redirect, so if you're planning to change the destination URL, 301 is not the right status code to use. On the other hand, 307 responses are not cached by default.
This is a follow up question to Using 301/303/307 redirects for dynamic short urls, where I try to determine the best method for implementing short url redirection when the destination url will change on a frequent basis. While it seems that 301 and 307 redirects both perform the same way, the issue that concerns me is 301 redirect caching (as documented here)- is the best way to avoid this to use 307 redirects instead (I'm assuming 307 redirects will never cache?), or to explicitly send a no-cache header ("Cache-Control: no-cache, must-revalidate")?
Avoiding 301 redirect caching
32 Guava contributor here: Yes, that looks just fine, although I'm not sure what the point is of wrapping the cache in another object. (Also, Cache.getIfPresent(key) is fully equivalent to Cache.asMap().get(key).) Share Improve this answer Follow answered Jun 20, 2012 at 17:59 Louis WassermanLouis Wasserman 194k2626 gold badges352352 silver badges421421 bronze badges 0 Add a comment  | 
I am trying to implement a high performance thread-safe caching. Here is the code I have implemented. I don't want any on demand computing. Can I use cache.asMap() and retrieve the value safely? Even if the cache is set to have softValues? import java.io.IOException; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; public class MemoryCache { private static MemoryCache instance; private Cache<String, Object> cache; private MemoryCache(int concurrencyLevel, int expiration, int size) throws IOException { cache = CacheBuilder.newBuilder().concurrencyLevel(concurrencyLevel).maximumSize(size).softValues() .expireAfterWrite(expiration, TimeUnit.SECONDS).build(); } static public synchronized MemoryCache getInstance() throws IOException { if (instance == null) { instance = new MemoryCache(10000, 3600,1000000); } return instance; } public Object get(String key) { ConcurrentMap<String,Object> map =cache.asMap(); return map.get(key); } public void put(String key, Object obj) { cache.put(key, obj); } }
Using Guava for high performance thread-safe caching
The following should cause the browsers to cache your images: <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" /> </staticContent> <httpProtocol> <customHeaders> <add name="Cache-Control" value="public" /> </customHeaders> </httpProtocol> The <caching>...</caching> block is for server-side caching, not client side caching.
I cannot get the image files to cache. I have tried everything that I have found on this site and others and still cannot get them to cache. Web config setting that I have tried <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" /> </staticContent> <httpProtocol allowKeepAlive="true" /> <caching enabled="true" enableKernelCache="true"> <profiles> <add extension=".png" policy="CacheUntilChange" /> <add extension=".jpg" policy="CacheForTimePeriod" duration="12:00:00" /> </profiles> </caching> Here is the response headers for 1 of the images Key Value Response HTTP/1.1 200 OK Cache-Control no-cache Content-Type image/png Last-Modified Thu, 16 Dec 2004 18:33:28 GMT Accept-Ranges bytes ETag "a1ca4bc9de3c41:0" Server Microsoft-IIS/7.5 X-Powered-By ASP.NET Date Fri, 18 May 2012 13:21:21 GMT Content-Length 775
IIS 7.5 and images not being cached
15 See the Memo pattern and the Scalaz implementation of said paper. Also check out a STM implementation such as Akka. Not that this is only local caching so you might want to lookinto a distributed cache or STM such as CCSTM, Terracotta or Hazelcast Share Improve this answer Follow edited May 23, 2017 at 12:25 CommunityBot 111 silver badge answered Sep 6, 2010 at 13:13 oluiesoluies 17.7k1414 gold badges7575 silver badges119119 bronze badges 2 1 Only that the Memo Pattern uses WeahHashMap and is therefore not a very good cache. – Debilski Sep 6, 2010 at 13:24 2 @Debilski Depends upon "cache" requirements. In this case a "weak cache" works to elevate the posters concerns that "cacheFun1 can [become too] large" .. – user166390 Nov 29, 2012 at 23:14 Add a comment  | 
This page has a description of Map's getOrElseUpdate usage method: object WithCache{ val cacheFun1 = collection.mutable.Map[Int, Int]() def fun1(i:Int) = i*i def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i)) } So you can use catchedFun1 which will check if cacheFun1 contains key and return value associated with it. Otherwise, it will invoke fun1, then cache fun1's result in cacheFun1, then return fun1's result. I can see one potential danger - cacheFun1 can became to large. So cacheFun1 must be cleaned somehow by garbage collector? P.S. What about object WithCache{ val cacheFun1 = collection.mutable.Map[Int, Int]() def fun1(i:Int) = i*i def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i)) } 0 ?
How to cache results in scala?
SQL Server does not have a results cache like MySQL or Oracle, so I am a bit confused about your question. If you want the server to recompile the plan cache for a stored procedure, you can execute it WITH RECOMPILE. You can drop your buffer cache, but that would affect all queries as you know. At my company, we test availability and performance separately. I would suggest you use this query just to make sure you your system is working together from front-end to database, then write other tests that check the individual components to judge performance. SQL Server comes with an amazing amount of ways to check if you are experiencing bottlenecks and where they are. I use PerfMon and DMVs extensively. Using PerfMon, I check CPU and page life expectancy, as well as seeing how long my disk queue is. Using DMVs, I can find out if my queries are taking too long (sys.dm_exec_query_stats) or if wait times are long (sys.dm_os_wait_stats). The two biggest bottlenecks with IIS tend to be CPU and memory, and IIS comes with its own suite of PerfMon objects to query, but I am not as familiar with those.
Having looked around the net using Uncle Google, I cannot find an answer to this question: What is the best way to monitor the performance and responsiveness of production servers running IIS and MS SQL Server 2005? I'm currently using Pingdom and would like it to point to a URL which basically mimics a 'real world query' but for obvious reasons do not want the query to run from cache. The URL will be called every 5 minutes. I cannot clear out the cache, buffers, etc since this would impact negatively on the production server. I have tried using a random generated number within the SELECT statement in order to generate unique queries, but the cached query is still used. Is there any way to simulate the NO_CACHE in MySQL? Regards
Prevent Caching in SQL Server
You can try to look at Terracotta framework Or you can use distributed Ehcache
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago. I need to implement a cache solution in java for a cluster of 9 servers with web applications. I saw apache JCS, seems old, do you know another open source solution?
Best cache framework for Java [closed]
After some research, a probable explanation is that the initialize_cache initializer is run way before the rails/initializers are. So if it's not defined earlier in the execution chain then the cache store wont be set. You have to configure it earlier in the chain, like in application.rb or environments/production.rb My solution was to move the APP_CONFIG loading before the app gets configured like this: APP_CONFIG = YAML.load_file(File.expand_path('../config.yml', __FILE__))[Rails.env] and then in the same file: config.cache_store = :redis_store, APP_CONFIG['redis'] Another option was to put the cache_store in a before_configuration block, something like this: config.before_configuration do APP_CONFIG = YAML.load_file(File.expand_path('../config.yml', __FILE__))[Rails.env] config.cache_store = :redis_store, APP_CONFIG['redis'] end
I'm trying to use redis-store as my Rails 3 cache_store. I also have an initializer/app_config.rb which loads a yaml file for config settings. In my initializer/redis.rb I have: MyApp::Application.config.cache_store = :redis_store, APP_CONFIG['redis'] However, this doesn't appear to work. If I do: Rails.cache in my rails console I can clearly see it's using the ActiveSupport.Cache.FileStore as the cache store instead of redis-store. However, if I add the config in my application.rb file like this: config.cache_store = :redis_store it works just fine, except the app config initializer is loaded after application.rb, so I don't have access to APP_CONFIG. Has anyone experienced this? I can't seem to set a cache store in an initializer.
Setting the cache_store in an initializer
What you are looking for is called Donut Caching. Here's a great article explaining what it is and how to make it work http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3
I have an issue with a partial View being cached when it shouldn't be. This partial View is used to display the Logon/Logoff on a page. It uses the simple code below to figure out which link to display @if(Request.IsAuthenticated) { <a href="@Url.Action("LogOff", "Account", new { area = "" })">Log Off</a> } else { <a href="@Url.Action("LogOn", "Account", new { area = "" })">Log On</a> } This partial View is called from with all pages in my MVC3 application, using @Html.Partial("_HeaderView") In most of my controllers, I have the output cache defined, so I can take advantage of caching my content. [OutputCache(Duration = 86400, VaryByParam = "*")] Now my issue is that the entire page is being cached when I don't want the partial view to be. This is causing wrong behavior where in it sometimes displays LogOff even if the user is not logged in etc. Is there a way to cache all the content, except for the partial view in question?
Disable caching on a partial view in MVC 3
Well, since Memcached doesn't store raw objects (it actually stores the serialiezd version), you can do this: $serializedFoo = serialize($foo); if (function_exists('mb_strlen')) { $size = mb_strlen($serializedFoo, '8bit'); } else { $size = strlen($serializedFoo); }
What's an appropriate way of measure a PHP objects actual size in bytes/kilobytes? Reason for asking: I am utilizing memcached for cache storage in my web application that will be used by non-technical customers. However, since memcached has a maximum size of 1mb , it would be great to have a function set up from the beginning that I can be used to measure size of selected objects/arrays/datasets, to prevent them from growing to big. Note that I am only planning on using this as a alert/diagnostic tool to keep track of the cache performance and storage possibilities over time. I assume that calculating speed on each memcached set/add call would slow down things a bit. I am also aware of storing big datasets in memcached takes away the whole idea of storing things in the RAM, and that is exactly why I need to know in beforehand to prevent customers building up to big datasets. Thanks a lot
PHP: Measure size in kilobytes of a object/array?
A simple solution would be to add query strings representing timestamp or session id to your files. For e.g., in our spring applications, we simply use : <script src="js/angular/lib/app.js?r=<%= session.getId()%>"></script> You can implement the same solution in your server specific implementation too.
Good morning, I have a web application in production environement. The users are using it every day, when I publish an update and a user comes back to the web application he views the old version of the web application. He needs to refresh the browser to load the new version. How can I solve this problem? I cannot tell hundreds of users to refresh the page every time I publish an update (3-4 times a week).
AngularJS browser cache issues
I found the source code DataFrame.cache def cache(self): """Persists the :class:`DataFrame` with the default storage level (`MEMORY_AND_DISK`). .. note:: The default storage level has changed to `MEMORY_AND_DISK` to match Scala in 2.0. """ self.is_cached = True self._jdf.cache() return self Therefore, the answer is : both
I want to know more precisely about the use of the method cache for dataframe in pyspark When I run df.cache() it returns a dataframe. Therefore, if I do df2 = df.cache(), which dataframe is in cache ? Is it df, df2, or both ?
cache a dataframe in pyspark
HttpContext.Current is available to all pages, but not necessarily to all threads. If you try to use it inside a background thread, ThreadPool delegate, async call (using an ASP.NET Async page), etc., you'll end up with a NullReferenceException. If you need to get access to the cache from library classes, i.e. classes that don't have knowledge of the current request, you should use HttpRuntime.Cache instead. This is more reliable because it doesn't depend on an HttpContext.
As per title. I want to be able to save some data in a cache object but this object must be available to all users/sessions and can expire. What is the best method to achieve this in a asp.net web app?
Is the HttpContext.Current.Cache available to all sessions
Update: npm run build && npm run start fixed it
I tried creating a new method inside AppController but it's not reflecting changes. I even tried to change the default getHello() method but it's outputting "Hello World!". How is this possible? Insomnia AppController AppService
Nest.Js not accepting any changes
You are right that topology constraints will, one way or another, increase latency of communication between cores, once the counts start going higher than a couple dozen. I don't really know what the intentions are of the x86 companies for dealing with that sort of scaling. But locks are implemented in terms of atomic operations. So you don't really win by trying to switch to them, unless they are implemented in a more scalable way than what you would be attempted with your own hand-rolled atomic operations. I think that generally, for single token-like contentions, atomic primitives will always still be the fastest way, regardless of how many cores you have. As Cray discovered long time ago, there's no free lunch here. High level software design, where you try to use potentially contentious resources in as infrequent as possible will always lead to the biggest payout in massively parallelized applications. This means doing as much work as possible as the result of a lock acquisition, but as quickly as possible as well. In extreme situations, this can mean pre-calculating your work on the assumption of a successfully acquired lock, trying to grab it, and just completing as fast as possible on success, otherwise throwing away your work and retrying on fail.
x86 and other architectures provide special atomic instructions (lock, cmpxchg, etc.) that allow you to write 'lock free' data structures. But as more and more cores are added, it seems as though the work these instructions will actually have to do behind the scenes will grow (at least to maintain cache coherency?). If an atomic add takes ~100 cycles today on a dual core system, might it take significantly longer on the 80+ core machines of the future? If you're writing code to last, might it actually be a better idea to use locks even if they're slower today?
Do atomic operations become slower as more CPUs are added?
The Application and Cache collections do not serialize the objects you pass into them, they store the actual reference. Retrieving an object from Cache will not be an expensive operation, no matter how large the object is. Always stick with the Cache objects unless you have a very good reason not to, its just good practice. The only other thing worth mentioning is to make sure you think about multithreaded access to this collection. You're going to end up with some serious issues very quickly if you don't lock properly
I am building a web-store with many departments and categories. They are stored in our database and accessed often. We are using URL rewriting so almost every request within the store generates a lookup. We also need to iterate over the data frequently to generate menus for the main store and the department pages. This information will not change often so I'm thinking that I should load the database into a dictionary to speed up the information retrieval. I know the standard practice is to load data into the application cache, however i assume that there is some level of serialization that occurs during caching, and for a large data-structure I'm thinking the overhead would be significant. My impulse on this is to put the dictionary in a static variable in one of the related classes. I would however like to get some input input on this. Am I right in thinking that this method would be faster? Is it horrible practice? Is there a better way that I'm missing? I can't seem to find much information on this and I'd really appreciate any information that you can share. Thanks!
Asp.net - Caching vs Static Variable for storing a Dictionary
add this between your HEAD tags <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1">
How do you make Firefox rerun javascript and reload the entire page when the user presses the back button? I was able to do this in all browsers except Firefox from the help of another SO question by adding this code: history.navigationMode = 'compatible'; $("body").unload(function(){}) And also adding an iFrame... But this doesn't work in Firefox. Is there anything to do?
Force Firefox to Reload Page on Back Button
Assuming that the smallest limit for html5 web storage is 5mb, it would be sensible to go with that answer given what information you have presented, and has been presented about W3C web storage. Do beware that everything is in flux, but I don't think this limit will change drastically.
I am looking into using browser sessionStorage for a web application, and was trying to find current information on size limitations. It appears most desktop browsers have imposed a 5MB limit. However, I am not finding many recent articles nor information on the mobile browsers. The Disk space of the W3C Web Storage specification says "A mostly arbitrary limit of five megabytes per origin is recommended. Implementation feedback is welcome and will be used to update this suggestion in the future." The QuirksMode HTML5 compatibility page for localstorage has its last major update on 12 June 2009 and only includes data for last years current browsers: IE8, FF 3.5b4, Saf 4, Chrome 2. According to Introduction to DOM Storage, IE8 "allows Web applications to store nearly 10 MB of user data." Introduction to sessionStorage seems to confirm that "Firefox’s and Safari’s storage limit is 5MB per domain, Internet Explorer’s limit is 10 MB per domain." Web Storage: easier, more powerful client-side data storage from the Opera developer site states "As of now, most browsers that have implemented Web Storage, including Opera, have placed the storage limit at 5 Mb per domain." A recent chromium issue (#42740) put a 5mb quota on session storage. Chapter 5. Client-Side Data Storage from Building iPhone Apps with HTML, CSS, and JavaScript states "At the time of this writing, browser size limits for localStorage and sessionStorage are still in flux." Question: Based on this info, should I just assume 5MB is the limit or should I spend time testing different browsers? Does anybody know of an existing test suite (a la Browserscope) that would have these results?
Is 5MB the de facto limit for W3C Web Storage?
25 If you check the source code, you'll notice that fetch does nothing more than call read and write. Since it does some other operations (like checking if a block has been given, etc.) one could say that fetch is heavier, but I think it's totally negligible. Share Improve this answer Follow edited Jun 4, 2015 at 17:34 eebbesen 5,15088 gold badges4949 silver badges7171 bronze badges answered Aug 24, 2014 at 18:05 beNjioxbeNjiox 47544 silver badges1212 bronze badges 3 1 If it does both read and write then what is the point of caching? It should write only if the data is updated, right? – Surya Sep 3, 2019 at 8:16 1 @LunaLovegood Rails.cache.fetch does a read if you pass it a single argument and does a write if you pass in a block. See: guides.rubyonrails.org/… – makstaks May 22, 2020 at 13:33 2 When passed only a single argument, the key is fetched and value from the cache is returned. If a block is passed, that block will be executed in the event of a cache miss. – sekmo Nov 1, 2021 at 15:46 Add a comment  | 
is there any performance difference between Rails.cache.fetch("key") { Model.all } and models = Rails.cache.read("key") if models.nil? models = Model.all Rails.cache.write("key", models) end If I must guess, i would say the upper one is just a shorthand for the other one.
Rails: cache.fetch vs cache.read/write
11 Our experience is that this folder gets cleared on app updates. It would be nice to know when exactly this folder is a candidate for being cleared. The docs describe this folder as location of discardable cache files (Library/Caches) The NSDocumentDirectory will not be cleared on app updates but be careful using this folder since iOS 5 now uses this folder for backing up in iCloud and your app will likely be rejected if you use this directory to store anything other then user generated content. Share Improve this answer Follow answered Nov 2, 2011 at 2:21 ChaseChase 11.2k88 gold badges4343 silver badges3939 bronze badges 5 12 Confirming that apps that use NSDocumentDirectory for storing content that's not user generated will be rejected. – Ciryon Nov 20, 2011 at 19:56 1 I can also confirm that Apple does check this. If you need to store files in the NSDocumentDirectory that can be rebuilt or downloaded make sure to flag them to be skipped during backup. Apple does allow this. – respectTheCode Jul 20, 2012 at 19:38 @Ciryon would it be okay to store images in NSDocumentDirectory that is being picked by the user in the camera roll? – Bazinga Aug 29, 2012 at 16:53 @respectTheCode, could you please explain a little bout your comment. Im using NSDocumentDirectory, and kinda scared of getting my app rejected. would It be good to redirect it in the NSCache folder? – Bazinga Aug 29, 2012 at 16:54 The NSDocumentDirectory can only be used for user created content or content that can not be recreated or downloaded. – respectTheCode Aug 31, 2012 at 14:01 Add a comment  | 
In what circumstances would files in the iOS NSCachesDirectory get removed? Obviously, delete and reinstall an application. What about application upgrade? What about low disk space conditions? Anything else?
When are files from NSCachesDirectory removed?
It determines whether or not your application classes are reloaded on each request. If it's true, you have to restart your server for code changes to take effect (i.e. you set it to true in production, false in development.) Documentation is here.
I was just wondering and didn't find explicit response on what in the model class (ActiveRecord) is cached when setting config.cache_classes to true ? Could someone tell me or point me to the doc I didn't found ? Thanks
Rails 4 : What is cached when using config.cache_classes = true
13 To rule out browser caching as the root cause, you might try adding the following lines: header('Cache-Control: no-store, private, no-cache, must-revalidate'); // HTTP/1.1 header('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false); // HTTP/1.1 header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Expires: 0', false); header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); header('Pragma: no-cache'); The combination of all these cache-busting HTTP headers has, in my experience, worked in all browsers, and has got around some very aggressive caching proxies as well. Share Improve this answer Follow edited Jan 29, 2017 at 5:49 Kyle Challis 1,04522 gold badges1414 silver badges2828 bronze badges answered Apr 19, 2010 at 13:43 Daniel WrightDaniel Wright 4,58422 gold badges2828 silver badges2828 bronze badges 1 Where exactly can I add these lines of code?Thanks in advance. – scruffycoder86 May 26, 2016 at 8:58 Add a comment  | 
So I opened the cache floodgates in my Cakephp app and now I want to close them... I've done pretty much everything I can: delete all files in the tmp folder (but not the folders), turned 'Cache.disable' on in the core.php file in my app, have tried clearing the cache from within some controllers with clearCache() and Cache::clear() (but I suspect this doesn't work because it's not loading the controller -- due to caching). I've pretty much effectively halted my development process just because caching won't turn off. Anyone have some ideas that I could try? I'm starting to think it may be within the browser or maybe my hosting service, but it's probably just Cakephp messing with me.
How do I completely disable caching in Cakephp?
I don't find any problem in going for a centralized cache using Redis. Anyway you are going to have a cluster setup so if a master fails slave will take up the position. If cache is flushed for some reason then you have to build the cache, in the mean time requests will get data from the primary source (DB) You can enable persistence and load the data persisted in the disk and can get the data in seconds(plug and play). If you think you will have inconsistency then follow the below method. Even if cache is not available system should work (with delayed time obviously). Meaning app logic should check for cache in redis if it's not there or system itself is not available it should get the value from dB and then populate it to redis and then serve to the client. In this way even if your redis master and slave are down your application will work fine but with a delay. And also your cache will be up to date. Hope this helps.
We're currently looking for the most suitable solution for accessing critical data on a distributed system, and we're considering whether to use in memory caching, versus a centralized cache. Some information about the data we wish to store/access: Very small data size Data is very cold; meaning it barely changes, and only changes when a human changes something in our back office system Has to be up to date when changed (a few 100ms delay is OK) Very critical path of our application, requires very high SLA (both in reliability and in response times (no more than 20ms to access)) Data is read from frequently (up to thousands of times per second) The way we see it is as following - In memory cache Pros: Quicker than network access + serialization Higher reliability in terms of distribution (if one instance dies, the data still exists on the other instances) Cons: Much more complex to code and maintain Requires notifying instances once a change occurs and need to update each instance seperately + Need to load data on start of each server Adds a high risk of data inconsistency (one instance having different or outdated data than others) Centralized cache For the sake of conversation, we've considered using Redis. Pros: Much simpler to maintain Very reliable, we have a lot of experience working with Redis in a distributed system Only one place to update Assures data consistency Cons: Single point of failure (This is a big concern for us); even though if we go with this solution, we will deploy a cluster What happens if cache is flushed for some reason
In-memory cache VS. centralized cache in a distributed system
14 Your best bet is Postsharp. I have no idea if they have what you need, but that's certainly worth checking. By the way, make sure to publish the answer here if you find one. EDIT: also, googling "postsharp caching" gives some links, like this one: Caching with C#, AOP and PostSharp UPDATE: I recently stumbled upon this article: Introducing Attribute Based Caching. It describes a postsharp-based library on http://cache.codeplex.com/ if you are still looking for a solution. Share Improve this answer Follow edited Feb 3, 2012 at 7:58 answered Mar 16, 2011 at 17:00 DypplDyppl 12.3k99 gold badges4949 silver badges6969 bronze badges 1 2 this code is great, i just downloaded it and used it for my project. however I had trouble because I am on a 64 bit pc and I think the demo is for x86. So I had to copy the code file by file. Works fine after that – samwa Oct 6, 2011 at 6:36 Add a comment  | 
Maybe this is dreaming, but is it possible to create an attribute that caches the output of a function (say, in HttpRuntime.Cache) and returns the value from the cache instead of actually executing the function when the parameters to the function are the same? When I say function, I'm talking about any function, whether it fetches data from a DB, whether it adds two integers, or whether it spits out the content of a file. Any function.
Caching attribute for method?
So it doesnt update a key's value. is this correct? That is correct. It will return the current value that was already in the Map. would this be a better impl for adding and updating cache? A couple things would make your implementation better. 1. You shouldn't use putIfAbsent to test if it exists, you should only use it when you want to ensure if one does not exist then putIfAbsent. Instead you should use map.get to test it's existence (or map.contains). V local = _cache.get(key); if (local.equals(value) && !local.IsExpired()) { return; } 2. Instead of put you will want to replace, this is because a race condition can occur where the if can be evaluated as false by two or more threads in which one of the two (or more) threads will overwrite the other thread's puts. What you can do instead is replace When all is said and done it could look like this public void AddToCache(T key, V value) { for (;;) { V local = _cache.get(key); if(local == null){ local = _cache.putIfAbsent(key, value); if(local == null) return; } if (local.equals(value) && !local.IsExpired()) { return; } if (_cache.replace(key, local, value)) return; } }
Java Docs says that, putIfAbsent is equivalent to if (!map.containsKey(key)) return map.put(key, value); else return map.get(key); So if the key exists in the map, it doesn't update its value. Is this correct? What if i want to update a keys value based on some criteria? Say expiration time etc. Would this be a better impl for adding and updating cache? public void AddToCache(T key, V value) { V local = _cache.putifabsent(key, value); if(local.equals(value) && local.IsExpired() == false){ return; } // this is for updating the cache with a new value _cache.put(key, value); }
ConcurrentHashMap put vs putIfAbsent
9 Use the experimental feature : Docker buildkit (Supported Since docker 18.09, docker-compose 1.25.4) In your dockerfile # syntax=docker/dockerfile:experimental FROM .... # ...... RUN --mount=type=cache,target=/var/composer composer install -n -o --no-dev Now before building, make sure the env var is exported: export DOCKER_BUILDKIT=1 docker build .... If you are using docker-compose, make sure to export also COMPOSE_DOCKER_CLI_BUILD : export COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose build ... If it does not work with docker-compose, make sure your docker-compose version is above 1.25.4 docker-compose version Share Improve this answer Follow edited Mar 13, 2020 at 18:14 answered Sep 14, 2019 at 10:13 Abdennour TOUMIAbdennour TOUMI 90k3939 gold badges256256 silver badges262262 bronze badges 5 1 What's the min version of the docker engine to use this experimental feature? – k0pernikus Sep 14, 2019 at 20:43 2 18.09 .. i will add it to the answer – Abdennour TOUMI Sep 14, 2019 at 20:46 2 And instead of exporting the var, one can also include it in the command itself: DOCKER_BUILDKIT=1 docker build . – k0pernikus Sep 16, 2019 at 10:09 @k0pernikus 😁 I am a Linux superman .. Or you can make alias . .or .. and or .. but the idea is that we are answering questions for the world wide. Considering backgrounds of everyone .. that's why. – Abdennour TOUMI May 1, 2020 at 22:26 Composer cache is located in /tmp/cache as of composer 1.10 – helvete Sep 22, 2020 at 9:44 Add a comment  | 
If I run composer install from my host, I hit my local composer cache: - Installing deft/iso3166-utility (1.0.0) Loading from cache Yet when building a container having in its Dockerfile: RUN composer install -n -o --no-dev I download all the things, e.g.: - Installing deft/iso3166-utility (1.0.0) Downloading: 100% It's expected, yet I like to avoid it. As even on a rebuilt, it would also download everything again. I would like to have a universal cache for composer that I could also reshare for other docker projects. I looked into this and found the approach to define a volume in the Dockerfile: ENV COMPOSER_HOME=/var/composer VOLUME /var/composer I added that to my Dockerfile, and expected to only download the files once, and hit the cache afterwards. Yet when I modify my composer, e.g. remove the -o flag, and rerun docker build ., I expected to hit the cache on build, yet I still download the vendors again. How are volumes supposed to work to have a data cache inside a docker container?
How to cache package manager downloads for docker builds?
Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Not easily. You'd have to write a custom serializer that hooks into the C sre implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required. First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory. If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above. Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application.
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Pickling the object simply does the following, causing compilation to happen anyway: >>> import pickle >>> import re >>> x = re.compile(".*") >>> pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." And re objects are unmarshallable: >>> import marshal >>> import re >>> x = re.compile(".*") >>> marshal.dumps(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: unmarshallable object
Caching compiled regex objects in Python?
After many weeks spent with offline caching, the answer is no, you either cache or don't cache, setting the cache attribute on the client side has no effect. You could consider offering an alternate url for the caching version, be aware that the page is also implicitly cached as a "master entry". I am at a loss to understand why you would want to offline cache jquery though, since it is likely to be served with very long expiry anyway. You may wish to consider offline storage as an alternative. Store the text of the scripts and inject them into the DOM on load. If not cached fetch using Ajax and inject the response, as creating a script tag with the src won't load the script.
I am using the new cache manifest functionality from HTML5 to cache my web app so it will work offline. The content is cached automatically when the page is loaded with the following html element: <html lang="en" manifest="offline.manifest"> This works fine. However, I want to give my users the option of whether they want the content cached offline. So, here is my question: Is there any way to trigger that an application be cached at runtime, using JavaScript, and not have it automatically done when the page is loaded. For example, something like this (using jquery): ----------------index.html-------------- <head> <meta charset="utf-8" /> <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="Main.js"></script> </head> <body> <button id="cacheButton">Cache Page</button> </body> </html> ---------Main.js--------- $(document).ready( function() { $('#cacheButton').click(onCacheButtonClick); } ) function onCacheButtonClick(event) { console.log("Setting Offline Manifest"); $('#htmlRoot').attr("manifest","offline.manifest"); } -------------offline.manifest------------- CACHE MANIFEST #version .85 #root index.html scripts/main.js #jquery assets http://code.jquery.com/jquery-1.4.4.min.js Basically, when the button is clicked, I dynamically set the manifest attribute of the html element. This works (in the sense the element is set), but it does not cause the browser to then cache the page. Any suggestions?
Dynamically Trigger HTML5 Cache Manifest file?
In order of speed: memcache cached HTML in data store full page generation Your caching solution should take this into account. Essentially, I would probably recommend using memcache anyways. It will be faster than accessing the data store in most cases and when you're generating a large block of HTML, one of the main benefits of caching is that you potentially didn't have to incur the I/O penalty of accessing the data store. If you cache using the data store, you still have the I/O penalty. The difference between regenerating everything and pulling from cached html in the data store is likely to be fairly small unless you have a very complex page. It's probably better to get a bunch of very fast cache hits off memcache and do a full regenerate every once in a while than to make a call out to the data store every time. There's nothing stopping you from invalidating the cached HTML in memcache when you update, and if your traffic is high enough to warrant it, you can always do a multi-level caching system. However, my main concern is that this is premature optimization. If you don't have the traffic yet, keep caching to a minimum. App Engine provides a set of really convenient performance analysis tools, and you should be using those to identify bottlenecks after you've got at least a few QPS of traffic. Anytime you're doing performance optimization, measure first! A lot of performance "optimizations" turn out to either be slower than the original, exactly the same, or they have negative user experience characteristics (like stale data). Don't optimize until you're certain you have to.
I have written a Google App Engine application that programatically generates a bunch of HTML code that is really the same output for each user who logs into my system, and I know that this is going to be in-efficient when the code goes into production. So, I am trying to figure out the best way to cache the generated pages. The most probable option is to generate the pages and write them into the database, and then check the time of the database put operation for a given page against the time that the code was last updated. Then, if the code is newer than the last put to the database (for a particular HTML request), new HTML will be generated and served, and cached to the database. If the code is older than the last put to the database, then I will just get the HTML direct from the database and serve it (therefore avoiding all the CPU wastage of generating the HTML). I am not only looking to minimize load times, but to minimize CPU usage. However, one issue that I am having is that I can't figure out how to programatically check when the version of code uploaded to the app engine was updated. I am open to any suggestions on this approach, or other approaches for caching generated html. Note that while memcache could help in this situation, I believe that it is not the final solution since I really only need to re-generate html when the code is updated (as opposed to every time the memcache expires).
Google App Engine - Caching generated HTML
Not sure if APC is the only solution but APC does take care of all your issues. First, your script will be compiled once with APC and the bytecode is stored in memory. If you have something taking long time to setup, you can also cache it in APC as user data. For example, I do this all the time, $table = @apc_fetch(TABLE_KEY); if (!$table) { $table = new Table(); // Take long time apc_store(TABLE_KEY, $table); } With APC, the task of creating table is only performed once per server instance.
I've been using rails, merb, django and asp.net mvc applications in the past. What they have common (that is relevant to the question) is that they have code that sets up the framework. This usually means creating objects and state that is persisted until the web server is recycled (like setting up routing, or checking which controllers are available, etc). As far as I know PHP is more like a CGI script that gets compiled to some bytecode each time it's run, and after the request it's discarded. Of course you can have sessions, to persist data between requests from the same user, and as I see there are extensions like APC, with which you can persist objects between requests at the server level. My question is: how can one create a PHP application that works like rails and such? I mean an application that on the first requests sets up the framework, then on the 2nd and later requests use the objects that are already set up. Is there some built in caching facility in mod_php? (for example that stores the compiled bytecode of the executed php applications) Or is using APC or some similar extensions the only way to solve this problem? How would you do it? Thanks. EDIT: Alternative question: if I create a large PHP application that has a very large set up time, but minor running time (like in the frameworks mentioned above) then how should I "cache" the things that are already set up (this might mean a lot of things, except for maybe the database connections, because for that you have persistent connections in PHP already). To justify large set up time: what if I'm using PHP reflection to check what objects are available and set the runtime according to that. Doing a lot of reflection is usually slow, but one has to do it only once (and re-evaluate only if the source code is modified). EDIT2: It seems it's APC then. The fact that it caches bytecode automatically is good to know.
How to persist objects between requests in PHP
Whether two maps is efficient depends entirely on how expensive getFromDatabase() is, and how big your objects are. It does not seem out of all reasonable boundaries to do something like this. As for the implementation, It looks like you can probably layer your maps in a slightly different way to get the behavior you want, and still have good concurrency properties. Create your first map with weak values, and put the computing function getFromDatabase() on this map. The second map is the expiring one, also computing, but this function just gets from the first map. Do all your access through the second map. In other words, the expiring map acts to pin a most-recently-used subset of your objects in memory, while the weak-reference map is the real cache. -dg
Off and on for the past few weeks I've been trying to find my ideal cache implementation using guava's MapMaker. See my previous two questions here and here to follow my thought process. Taking what I've learned, my next attempt is going to ditch soft values in favor of maximumSize and expireAfterAccess: ConcurrentMap<String, MyObject> cache = new MapMaker() .maximumSize(MAXIMUM_SIZE) .expireAfterAccess(MINUTES_TO_EXPIRY, TimeUnit.MINUTES) .makeComputingMap(loadFunction); where Function<String, MyObject> loadFunction = new Function<String, MyObject>() { @Override public MyObject apply(String uidKey) { return getFromDataBase(uidKey); } }; However, the one remaining issue I'm still grappling with is that this implementation will evict objects even if they are strongly reachable, once their time is up. This could result in multiple objects with the same UID floating around in the environment, which I don't want (I believe what I'm trying to achieve is known as canonicalization). So as far as I can tell the only answer is to have an additional map which functions as an interner that I can check to see if a data object is still in memory: ConcurrentMap<String, MyObject> interner = new MapMaker() .weakValues() .makeMap(); and the load function would be revised: Function<String, MyObject> loadFunction = new Function<String, MyObject>() { @Override public MyObject apply(String uidKey) { MyObject dataObject = interner.get(uidKey); if (dataObject == null) { dataObject = getFromDataBase(uidKey); interner.put(uidKey, dataObject); } return dataObject; } }; However, using two maps instead of one for the cache seems inefficient. Is there a more sophisticated way to approach this? In general, am I going about this the right way, or should I rethink my caching strategy?
my ideal cache using guava
You can try this, in your AppDelegate.m +(void)initialize { [[NSURLCache sharedURLCache] setDiskCapacity:0]; [[NSURLCache sharedURLCache] setMemoryCapacity:0]; }
I use a UIWebView to load a local html, and there is a PNG file inside the html created by Objc. After the PNG file has been modified, I reload the html in UIWebView, but the image doesn't change. However, if I quit the app and reopen it, the image file will be changed to the new one. I have checked the PNG file in Documents with Finder, so I'm sure it has been modified, but the old one is still in UIWebView. So, as I think that it's a UIWebView cache problem, I've tried: [[NSURLCache sharedURLCache] removeAllCachedResponses]; [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:url isDirectory:NO ] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:1]]; or NSURLRequestReloadIgnoringCacheData None of them works, and I can't change the filename, because the PNG file is used in a lot of places (other html and objc code). I've tried this too: some.png?r=randomNumber but it can't be showed. How do I clear the UIWebView cache when using a local image file inside a local html?
Clear UIWebView cache when use local image file
The # Bytes in all Heaps is only updated when the garbage collection is executed, while the Private Bytes is available at much faster update rate. (I'm not sure where that number comes from, internally, and how often it's updated.) The amount of Private Bytes increases just after 17:42:45. This amount does seem to match the value jump of # Bytes in all Heaps at about 17:43:10. It looks like it took 20-25 seconds before any garbage collection was done and updated the # Bytes in all Heapscounter. It's hard to work out how memory allocations work from a few minutes worth of performance counters presented in a screenshot. ;) Keep running your test and see how your expectations work out over a longer time period. TL;DR: The amount of managed bytes should correlate with private bytes, but the managed counter will only update during a garbage collection. Small note from the OP: As this response says, the lagging in the memory can be fully explained by lagging GC. The fact that unmanaged memory also rises was not my question. So thanks @Simon.
OK, all you ASP.NET Experts: I have used reflector to look into ASP.NET Cache implementation (which sits on HttpRuntime.Cache and HttpContext.Current.Cache) uses a Hashtable internally to keep the cache. However, the data gets stored in unmanaged memory. This is very strange since I could not see anywhere data getting stored in unmanaged memory. However, writing a very simple web application that inserts a chunk of byte array into cache, we can see this: Private Bytes: 460MB Bytes in all heaps: 150MB => Managed Memory: 150 MB Unmanaged Memory: 310 MB So basically I am calling the application many times (each increase is 1000x requests each putting 64KB empty buffer byte[] into cache). So the one that has grown the most is private bytes (total memory) instead of bytes in all heaps (managed memory). However I am expecting managed memory to grow in line with total memory since I am adding objects to the managed heap using Hashtable. Can you please explain this behaviour? UPDATE As Simon said, the bytes in all heaps value only changes after a garbage collection - I changed the code to induce garbage collection and it update the counters. Increase in Gen 2 Heap memory is EXACTLY the same as the amount of memory added. However, unmanaged memory is still much higher. In this example, Heap 2 was only 96MB while total memory 231 MB.
Why (and how) ASP.NET Cache gets stored in Unmanaged Memory?
A small feature comparison is here: http://toddrobinson.com/appfabric/appfabric-cache-feature-comparisons/ UPDATE 25.02.2016 Dead link fixed thanks to WebArchive.org: http://web.archive.org/web/20140205010302/http://toddrobinson.com/appfabric/appfabric-cache-feature-comparisons/
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 One of the decisions I need to make is what caching framework to use in my system. With so many to choose from, I am currently investigating redis, ehcache and memcached. Can anyone point to performance benchmarks of these three particular frameworks? Also an overview of their features - I am particularly interested in disadvantages, ie. situations where you would use one over the other.
Comparison of memcache, redis and ehcache as distributed caching framework [closed]
3 Make sure it's using the correct cache. Try from django.core.cache import caches, and then see the contents of caches.all(). It should just have one instance of django.core.cache.backends.memcached.MemcachedCache. If it is, try accessing that directly, e.g. from django.core.cache import caches m_cache = caches.all()[0] m_cache.set("stack","overflow",3000) m_cache.get("stack") This might not solve your problem, but will at least get you closer to debugging Memcached instead of Django's cache proxy or your configuration. Share Improve this answer Follow answered Aug 5, 2015 at 20:50 Jake KreiderJake Kreider 97077 silver badges1212 bronze badges 0 Add a comment  | 
When I run python manage.py shell and then: from django.core.cache import cache cache.set("stack","overflow",3000) print cache.get("stack") (output: ) None I tried restarting memcache, and here is what's in my settings: CACHES = { 'default' : { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION' : '127.0.0.1:11211', } }
Django Cache cache.set Not storing data
When you are logged as an admin (obviously, not every user of the site has to power to clear the cache), there should be a page in "Administer > Site Configuration > Performance". And, at the bottom of the page, there should be a button (something like "Clear cached data") to clear the cache As far as I remember, there's no need for Devel to do that, and you really don't need to go to the database, nor run some home-made PHP code. As a reference, you can take a look at How to Clear Drupal Server-side cache
How do I empty the Drupal caches: without the Devel module without running some PHP Statement in a new node etc. without going into the database itself Effectively, how do you instruct an end user to clear his caches?
How do I empty Drupal Cache (without Devel)
Didn't work with Django yet, but here's my default approach for checking if some component actually writes to redis during development: First, I flush all keys stored in redis in order to remove old cache entries (never do this in production as this removes all data from redis): > redis-cli FLUSHALL Then activate caching in my application, and see what redis does: > redis-cli MONITOR You should enter an interactive session where you see every command sent to redis. Reload your page and on your terminal you should see some SET* operations storing the cache data. Reload again and if your cache works, you should see some GET* operations retrieving the cached data. Note: with this method you can check if your cache is actually used. What you can't see is if your cache helps speeding up your application. For that you have to do performance tests as suggested in the comments.
I've installed django-redis-cache and redis-py. I've followed the caching docs for Django. As far as I know, the settings below are all that I need. But how do I tell if it's working properly?? settings.py CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '<host>:<port>', 'OPTIONS': { 'DB': mydb, 'PASSWORD': 'mydbspasswd', 'PARSER_CLASS': 'redis.connection.HiredisParser' }, }, } ... MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', ...[the rest of my middleware]... 'django.middleware.cache.FetchFromCacheMiddleware', ) CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = (60 * 60) CACHE_MIDDLEWARE_KEY_PREFIX = ''
How can I test if my redis cache is working?
In order to have a list of cached items by ViewPager I changed my Custom Adapter which an extension FragmentStatePagerAdapter: Add a HashMap<Integer, FragmentDipsplayPageContent> cachedFragmentHashMap to my adapter Update getItem() method like this public Fragment getItem(int index) { Fragment fragment = new FragmentDipsplayPageContent(); Bundle args = new Bundle(); args.putInt("INDEX", index); fragment.setArguments(args); cachedFragmentHashMap.put(index,fragment); return fragment; } Update destroyItem() method of adapter like this @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); //add this line to remove fragments wiped from ViewPager cache cachedFragmentHashMap.remove(position); } Add a getter to access HashMap of cached Fragments from activity: public HashMap<Integer, FragmentDipsplayPageContent> getCachedFragmentHashMap() { return cachedFragmentHashMap; } update using this collection inside activity: private void increaseFontSizeForCachedFragments() { HashMap<Integer, FragmentDipsplayPageContent> cachedFragmentsHashMap = adapterViewPager .getCachedFragmentHashMap(); Collection<FragmentDipsplayPageContent> fragmentsCollection = cachedFragmentsHashMap .values(); for (FragmentDipsplayPageContent fragmentDipsplayPageContent : fragmentsCollection) { //update views of fragment fragmentDipsplayPageContent.increasTextFontSize(); } } This way all cached fragments including visible and off-screen fragments are updated.
I have a ViewPager which contains several TextViews inside its fragment which they have different font sizes. In addition, I got buttons for increase/decreasing font size which calculate font size of each textView by adding its default size plus a value called STEP (which changes by inc/dec font size button). My problem is if a view is displayed for first time after applying size changes, It will create textViews in desired size during onCreateView() however if fragment was cached already and onCreateView is not called again, I don't know how to update their textViews considering only one of cached fragments is displaying on screen (and i can update it with no problem) but others are not displayed (I don't know if they are attached to activity or not in this case). In other words how can i detect which fragments are cached by ViewPager and their onCreateView already called (these are fragments which update to their views must be applied). I marked them in light green with question marks in below picture:
Android ViewPager: Update off-screen but cached fragments in ViewPager
14 Have you checked the request headers? "‘Cache-Control’ is always set to ‘max-age=0′, no matter if you press enter, f5 or ctrl+f5. Except if you start Chrome and enter the url and press enter." http://techblog.tilllate.com/2008/11/14/clientside-cache-control/ Share Improve this answer Follow answered Feb 1, 2011 at 11:40 Petteri HPetteri H 11.9k1212 gold badges6565 silver badges9494 bronze badges 0 Add a comment  | 
I have a page with lots of small images (icons). When used with chrome, each time the page is reloaded, chrome requests each icon from the server with if-modified-since header. All icons are served with expires and max-age headers. Firefox loads images from its cache. Why is chrome doing that and how can I prevent it? Thanks
Chrome - why is it sending if-modified-since requests?
The solution is using the system.webserver section in the web.config file to configure server caching (and compression). Here is a starting point: http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache Example: <configuration> <system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" /> <!-- 1 day --> </staticContent> </system.webServer> </configuration>
We have a Webforms project with url routing. I have defined exception routes for images and css-files as routes.Add("IgnoreImages", new Route("img/{*pathInfo}", new StopRoutingHandler())); routes.Add("IgnoreCss", new Route("css/{*pathInfo}", new StopRoutingHandler())); so static files should be served by IIS directly and routing should be bypassed. When checking the response for an image with Fiddler the only key under the Cache heading is Date. What's missing is the Cache-control:max:age key. How can I specify caching policy for static files? The application is run on IIS7.5.
Get Asp.net/iis to set Cache-control:max-age for static files
As applications grow it is quite normal to leverage caching as a way to gain scalability and keep consistent server response times. Caching works by storing data in memory to drastically decrease access times. To get started I would look at ASP.NET caching. There are 3 types of general Caching techniques in ASP.NET web apps: Page Output Caching(Page Level) Page Partial-Page Output(Specific Elements of the page) Programmatic or Data Caching Output Caching Page level output caching caches the html of a page so that each time ASP.NET page requested it checks the output cache first. You can vary these requests by input parameters(VaryByParam) so the the page will only be cached for users where ID=1 if a requests come in where ID=2 asp.net cache is smart enough to know it needs to re-render the page. Partial-Page Caching a lot of times it wont make sense to cache the entire page in these circumstances you can use partial Page caching. This is usually used with user controls and is set the same way as page level only adding the OutputCache declarative inside the usercontrol. Data Caching You can store objects or values that are commonly used throughout the application. It can be as easy to as: Cache["myobject"] = person; Enterprise Level Caching It is worth mention that there are many Enterprise level caching architectures that have come about to leverage the effectiveness caching. Memcache for .net and Velocity(now App Fabric) are a couple. In General You can't really make blanket statements on what you should and shouldn't cache because every application is different. However, you can make a few generalizations that hold true MOST of time. Static elements like images and content are OK to cache. Even a dynamic page that is getting hammered is worth caching for 5-10 seconds, it will make a world of difference to your web server.
I am interested in using the ASP.NET Cache to decrease load times. How do I go about this? Where do I start? And how exactly does caching work?
How does the ASP.NET Cache work?
Variables are stored in the session, so if you close your powershell console and open a new one, all custom variables will be gone. If you want to see what variables exists, use Get-Variable . To delete a specific variable(to make sure it's gone), you could use: Remove-Variable varname. As for you question. A variable in the global(session) scope is stored in the session until it's removed or overwritten. If you used the same powershell console to run that code twice, then $inpath should have been set to "C:\temp\tx" the second time, and $srcfiles would be updated with the new filelist.
This morning, I copied a directory from my local, networked drive to temp folder for testing. This error appeared. Get-Content : Cannot find path 'C:\users\xxxxx\desktop\cgc\Automatic_Post-Call_Survey_-_BC,_CC.txt' because it does no t exist. At C:\users\xxxxx\desktop\cgc\testcountexcl1.ps1:55 char:12 + Get-Content <<<< $txtfile | Get-WordCount -Exclude (Get-Content c:\temp\exclude.txt) | select -First 15 + CategoryInfo : ObjectNotFound: (C:\users\xxxxx...ey_-_BC,_CC.txt:String) [Get-Content], ItemNotFoundEx ception + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand This would be expected with the move...PS can't find the path referenced...but I made the following change prior to running the script (old commented out above the new): $input = Get-Content c:\temp\wordCount.txt <# $inpath = "C:\users\xxxxx\desktop\cgc\tx" #> $inpath = "C:\temp\tx" $srcfiles = Get-ChildItem $inpath -filter "*.txt" $notPermittedWords = Get-Content c:\temp\exclude.txt My first inkling is that there's some kind of cache holding my $inpath variable from my last run...but have not been able to find out if that's expected PowerShell behavior. Am I misinterpreting the error or the solution? How do I flush the cache or whatever varables may be stored in memory?
Does Powershell have a cache that needs to be cleared?
18 I am using phpFastCache ( for shared hosting, if you don't want to touch php.ini and root to setup memcached). Check out the Example Menu. They have full detail example, and very easy. First you set with phpFastCache::set and then get with phpFastCache::get - DONE! Example: Reduce Database Calls Your website have 10,000 visitors who are online, and your dynamic page have to send 10,000 same queries to database on every page load. With phpFastCache, your page only send 1 query to DB, and use the cache to serve 9,999 other visitors. <?php // In your config file include("php_fast_cache.php"); phpFastCache::$storage = "auto"; // you can set it to files, apc, memcache, memcached, pdo, or wincache // I like auto // In your Class, Functions, PHP Pages // try to get from Cache first. $products = phpFastCache::get("products_page"); if($products == null) { $products = YOUR DB QUERIES || GET_PRODUCTS_FUNCTION; // set products in to cache in 600 seconds = 5 minutes phpFastCache::set("products_page",$products,600); } OUTPUT or RETURN your $products ?> Share Improve this answer Follow edited May 7, 2013 at 2:34 answered Apr 29, 2013 at 10:00 Ken LeKen Le 1,79722 gold badges2222 silver badges3434 bronze badges 2 +1 for the example and one that works with shared hosting. Cheers! – Mario Awad Aug 6, 2013 at 11:36 how can you use this class? can you answer my question? stackoverflow.com/questions/22116573/how-to-use-phpfastcache – Mohammad Fanni Mar 1, 2014 at 18:13 Add a comment  | 
How to cache PHP page which has mysql query. Any example will be great and helpful.
How to cache dynamic PHP page
shared hit essentially means the value has already been cached in the main memory of the computer and it was not necessary to read this from the hard disk. Accessing the main memory (RAM) is much faster than reading values from the hard disk. And that's why the query is faster the more share hits it has. Immediately after starting Postgres, none of the data is available in the main memory (RAM) and everything needs to be read from the hard disk. Consider this step from an execution plan: -> Seq Scan on products.product_price (cost=0.00..3210.27 rows=392273 width=0) (actual time=0.053..103.958 rows=392273 loops=1) Output: product_id, valid_from, valid_to, price Buffers: shared read=2818 I/O Timings: read=48.382 The part "Buffers: shared read=2818" means that 2818 blocks (each 8k) had to be read from the hard disk (and that took 48ms - I have a SSD). Those 2818 blocks were stored in the cache (the "shared buffers") so that the next time they are needed the database does not need to read them (again) from the (slow) hard disk. When I re-run that statement the plan changes to: -> Seq Scan on products.product_price (cost=0.00..3210.27 rows=392273 width=0) (actual time=0.012..45.690 rows=392273 loops=1) Output: product_id, valid_from, valid_to, price Buffers: shared hit=2818 Which means that those 2818 blocks that the previous statement were still in the main memory (=RAM) and Postgres did not need to read them from the hard disk. "memory" always refers to the main memory (RAM) built into the computer and directly accessible to the CPU - as opposed to "external storage". There are several presentations on how Postgres manages the shared buffers: http://de.slideshare.net/EnterpriseDB/insidepostgressharedmemory2015 http://momjian.us/main/writings/pgsql/hw_performance/ https://2ndquadrant.com/media/pdfs/talks/InsideBufferCache.pdf (very technical) http://raghavt.blogspot.de/2012/04/caching-in-postgresql.html
I'm experimenting with the EXPLAIN command and trying to find out what the shared hit is. Seq Scan on foo (cost=0.00..18334.00 rows=1000000 width=37) (actual time=0.030..90.500 rows=1000000 loops=1) Buffers: shared hit=512 read=7822 Total runtime: 116.080 ms I've noticed that the more shared hit number we have the faster a query is being executed. But what is that? As far as I got, shared read is just reading from a physical storage like RAID or SSD. But why is the shared hit faster? Is it stored inside RAM or where?
Shared hit cache in postgreSQL
Reusing the selector reference, your first case, is definitely faster. Here's a test I made as proof: http://jsperf.com/caching-jquery-selectors The latter case, redefining your selectors, is reported as ~35% slower.
Is it recommended that, when I need to access the result of a jQuery selector more than once in the scope of a function, that I run the selector once and assign it to a local variable? Forgive my trite example here, but i think it illustrates the question. So, will this code perform faster: var execute = function(){ var element = $('.myElement'); element.css('color','green'); element.attr('title','My Element'); element.click(function(){ console.log('clicked'); }); } than this code: var execute = function(){ $('.myElement').css('color','green'); $('.myElement').attr('title','My Element'); $('.myElement').click(function(){ console.log('clicked'); }); } If there is no difference, can anyone explain why? Does jQuery cache elements after selecting them so subsequent selectors don't have to bother searching the dom again?
Performance of jQuery selectors vs local variables
OK. The code is fine above. The permission needed to be added are: .INTERNET .ACCESS_NETWORK_STATE .ACCESS_WIFI_STATE
I have an application which loads urls from a website. Now I want the application to use the cache when offline. But I just get the failure page which says that im not connected to the website. At first I set the Cachemode to Load_Normal but this doesn't help. Next I tried a realy "silly" approach using the ConnectivityManager: cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE); if(cm.getActiveNetworkInfo().isConnected()){ mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); mfnWebView.loadUrl(url); } else{ mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); mfnWebView.loadUrl(url); } but this just leads to crashing the application. Is there a simple way to load the cache when offline and existing and just if not existing showing the failure message.
Loading Cache when Offline in Android Webview
17 You can use the option --touch to mark them up to date: --touch, -t Touch output files (mark them up to date without really changing them) instead of running their commands. This is used to pretend that the rules were executed, in order to fool future invocations of snakemake. Fails if a file does not yet exist. Beware that this will touch all your files and thus modify the timestamps to put them back in order. Share Improve this answer Follow edited Jun 28, 2019 at 9:57 answered Jun 28, 2019 at 9:37 Eric C.Eric C. 3,36022 gold badges2222 silver badges2929 bronze badges Add a comment  | 
Even if the output files of a Snakemake build already exist, Snakemake wants to rerun my entire pipeline only because I have modified one of the first input or intermediary output files. I figured this out by doing a Snakemake dry run with -n which gave the following report for updated input file: Reason: Updated input files: input-data.csv and this message for update intermediary files reason: Input files updated by another job: intermediary-output.csv How can I force Snakemake to ignore the file update?
How to avoid running Snakemake rule after input or intermediary output file was updated
The Spring Boot starter provides a simple cache provider which stores values in an instance of ConcurrentHashMap. This is the simplest possible thread-safe implementation of the caching mechanism. If the @EnableCaching annotation is present in your app, Spring Boot checks dependencies available on your class path and configures an appropriate CacheManager. Depending on a chosen provider, some additional configuration may be required. You can find all information about configuration in the first link from this answer.
I have implemented caching in my SpringBootApplication as shown below @SpringBootApplication @EnableCaching public class SampleApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SampleApplication.class); } public static void main(String[] args) { SpringApplication.run(SampleApplication.class, args); } This is absolutely working fine. But to implement caching there should be one mandatory CacheManager / Cacheprovider defined. Without defining any cacheManager also my application is working fine. Is there any default Cache manager defined by Spring ? Spring docs says Spring Boot auto-configures a suitable CacheManager. So what will be CacheManager used if we do not define it ?
Default Cache Manager with Spring Boot using @EnableCaching
Keep it as instance member of the containing class. In web app you can't do this since page class's object is recreated on every request. However .NET 4.0 also has MemoryCache class for this purpose.
I need to cache a generic list so I dont have to query the databse multiple times. In a web application I would just add it to the httpcontext.current.cache . What is the proper way to cache objects in console applications?
Caching in a console application
Development server was running various caching tools though they should have been turned off. After disabling them chrome started to work better and most of the time CTRL+F5 did the trick.
I am working on a new site and whenever I change CSS settings chrome will not accept those changes unless I close out of chrome completely with Task manager and relaunch it. I have a tried quite a few things. Below is a list of things I've tried: Versioning the CSS file (I am using a PHP date stamp at the end of the CSS file Enabling "Clear Cache while developer window is open" in the Developer console Using Ctrl + F5 to clear cache on refresh Going to Application and Clear Storage in the developer Console Clearing Cache folder in local AppData Deleting CSS file from stie, refreshing, and readding file. Incognito mode Adding Launch options to chrome shortcut --disk-cache-dir=null Adding Browser Plugins to delete cache. Anyone have any ideas how to help? It is extremely annoying and inefficient to close chrome every time I want to check a CSS change. Another annoyance is that I am trying to listen to music in the browser so if I close chrome I have to go back and get my music playing again and it's just as of now extremely annoying and way more time consuming than I want. I've tried looking at other articles online about cache busting and other articles on Stack Overflow but I've tried to do most of what they suggest and I haven't seen any positive outcome yet. Most articles say to add some sort of random string or version on the end of the CSS file as a GET request but that isn't working though I know that has worked for me in the past.
Chrome is not clearing cache
You should check out the git-cache-http-server project. I think it partly implements what you need (and is similar to the idea from @larsks post). It is a NodeJS piece of software that runs an HTTP server to provide you access to locally cached git repositories. The server automatically does fetch upstream changes when required. If you use those local git repositories instead of the distant ones, your git client will be served locally cached content. If you run the git-cache-http-server on a separate host (VM or container for example), you can configure your local git client to automatically clone and fetch from the cache by configuring it to replace https://github.com with something like http://gitcache/github.com. This can be achieved by a configuration like: git config --global url."http://gitcache:1234/".insteadOf https:// At the moment, this software only provides a cache to clone and update a repository, there is no provision for pushing changes back. For some use cases, thinking about a CI infrastructure that needs to pull content of multiple repositories even when only a single one has changed or the automated testing you mention, this can be useful.
We use github to manage a great deal of our software environment, and I would wager that like many other orgs the overwhelming majority of traffic to/from that repo comes from our office. With that in mind, is there a way to build a local cache of a given github repository, but still have the protection of the cloud version? I'm thinking of this in the model of a caching proxy server, where the local server (presumably in our building, on our local network) would handle the vast majority of cloning/pull operations. This seems like it should be doable, but searching for this has been very difficult, I think in no small part because the words "local" and "cache" have overloaded meanings especially for git(hub) questions.
local cache for a github repository?
Actually there are some things you can do: Either you disable your browser caching completely to test it. An easy way in e.g. Chrome is to open a Incognito Window (CTRL + SHIFT + N) similar to the Private Browsing mode in Firefox. However the more ideal solution for you should be listed here: Disabling Chrome cache for website development Or you instruct your webserver to send no cache headers for javascript or some javascript files. One possibility is to use mod_expires with apache.
Using require.js I noticed that often the dependencies are cached by the browser and don't get updated even if I force the page to completely reload (command+shift+R). In order to have always the updated file, I made require.js ask for the files adding '?datestamp' after the url. The only problem with this approach is that the breakpoints don't remain in chrome or firebug after reloading, making the debug painful. Do you have any suggestion?
Debugging when using require.js cache
Runtime caching using Workbox sw. service-worker.js: importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-sw.dev.v0.0.2.js'); importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-runtime-caching.prod.v1.3.0.js'); importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-routing.prod.v1.3.0.js'); const assetRoute = new workbox.routing.RegExpRoute({ regExp: new RegExp('^http://localhost:8081/jobs/static/*'), handler: new workbox.runtimeCaching.CacheFirst() }); const router = new workbox.routing.Router(); //router.addFetchListener(); router.registerRoutes({routes: [assetRoute]}); router.setDefaultHandler({ handler: new workbox.runtimeCaching.CacheFirst() }); Script in my html file to load Servcie worker. <script> if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('http://localhost:8081/jobs/static/service-worker.js?v=4').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); }); } </script>
In service worker, I can define array of resource those are being cached during service worker get started mentioned below: self.addEventListener('install', event => { event.waitUntil(caches.open('static-${version}') .then(cache => cache.addAll([ '/styles.css', '/script.js' ])) ); }); How can I define a path/directory in service worker, so that instead of writing all files name, service worker pick all files from given path/directory and add all in cache?
Is there any way to cache all files of defined folder/path in service worker?
Suggestions made so far have been great, but my need is still as stated: to iterate over the cache's items. It seems like such a simple task, and I expect that the cache internally has some sort of list structure anyway. The docs and the feature set for MemoryCache are wanting. So as discussed above, I've added a list to my cache adapter class, which holds a reference to each item I place in the cache. If I need to iterate over the cache--not just for invalidation, but for gathering statistics, etc.--then I iterate over my list. If the number of items placed in the cache does not change, then this is a reasonable solution. If the number does change, then you need to insert/remove via the adapter class, so as to keep the list in sync with the actual cache. Messy but it works, and avoids the perf penalties alluded to in the docs. Hopefully MemoryCache cache provider will be fleshed-out in the next platform release.
I'm using the cache provided by System.Runtime.Caching.MemoryCache. I'd like to enumerate over the cache's items so that I can invalidate (evict then reload) items as such foreach (var item in MemoryCache.Default) { item.invalidate() } But the official docs found here state: !Important: Retrieving an enumerator for a MemoryCache instance is a resource-intensive and blocking operation. Therefore, the enumerator should not be used in production applications. Surely there must be a simple and efficient way to iterate over the cache's items?
Can I iterate over the .NET4 MemoryCache?
3 +125 Almost any complicated logic quickly goes out of control if you use plain rxjs. I would rather implement custom cache operator from scratch, you can use this gist as an example. Share Improve this answer Follow answered Feb 18, 2017 at 23:25 kemskykemsky 14.9k33 gold badges3434 silver badges5252 bronze badges Add a comment  | 
I am using RsJS 5 (5.0.1) to cache in Angular 2. It works well. The meat of the caching function is: const observable = Observable.defer( () => actualFn().do(() => this.console.log('CACHE MISS', cacheKey)) ) .publishReplay(1, this.RECACHE_INTERVAL) .refCount().take(1) .do(() => this.console.log('CACHE HIT', cacheKey)); The actualFn is the this.http.get('/some/resource'). Like I say, this is working perfectly for me. The cache is returned from the observable for duration of the RECACHE_INTERVAL. If a request is made after that interval, the actualFn() will be called. What I am trying to figure out is when the RECACHE_INTERVAL expires and the actualFn() is called — how to return the last value. There is a space of time between when the RECACHE_INTERVAL expires and the actualFn() is replayed that the observable doesn't return a value. I would like to get rid of that gap in time and always return the last value. I could use a side effect and store the last good value call .next(lastValue) while waiting for the HTTP response to return, but this seems naive. I would like to use a "RxJS" way, a pure function solution — if possible.
Reactive Caching of HTTP Service
The easiest way is save webpages in cache directory or any other(Internal or external storage) You can get the data of web page using HttpClient.execute() or HttpClient.get() now store that data in .html file also you have to download images or other contents which are bind to that page, Now in your application you have to check for connection if connection not available then load the page which one you saved in storage with file://<location of your webpage..> EDIT: I think using HTML5 you can display off-line webpages. (I never tried this, but I referred some blogs on it). Look at this nice post about HTML5 Creating mobile Web applications with HTML 5, Part 3: Make mobile Web applications work offline with HTML 5 Also this hope this will help you.
I am working on an application where I load few websites in webview now I want to save webpages so after sometime even if there is not internet user will able to see those pages. But I am confused on how to save whole webpage in cache or any other medium. The main thing is we need to show pages back even if there is not internet. Has anyone implemented this before. Please provide some demo code as this is my first attempt on cache.. Thank You
Saving webpage in cache using webview in android
Cacheing is handled application-wide by NSURLCache. If you don't set a shared cache, requests are not cached. Even with a shared NSURLCache, the default implementation on iOS does not support disk cacheing anyway. That said, unless you have a very particular reason to write your own cacheing system, I would strongly recommend against it. NSURLCache is good enough for 99.9% of applications: it handles cache directives from incoming responses and uses them appropriately with new requests, and does so automatically in a way that is unlikely to be a performance bottleneck in your application. As someone who has wasted untold hours making one myself (and later throwing it away since it was completely unnecessary), I'd say that there are much better places to focus your development attention.
Is it possible to disable all the cache features from AFNetworking? I am building my own custom cache system and don't want this to take up disk space too. Thanks, Ashley
How To Disable AFNetworking Cache
You're liable to end up with tests stomping on each other. You should wrap this up with ensure and reset it to old values appropriately. An example: module ActionController::Testing::Caching def with_caching(on = true) caching = ActionController::Base.perform_caching ActionController::Base.perform_caching = on yield ensure ActionController::Base.perform_caching = caching end def without_caching(&block) with_caching(false, &block) end end I've also put this into a module so you can just include this in your test class or parent class.
Generally, I want my functional tests to not perform action caching. Rails seems to be on my side, defaulting to config.action_controller.perform_caching = false in environment/test.rb. This leads to normal functional tests not testing the caching. So how do I test caching in Rails 3. The solutions proposed in this thread seem rather hacky or taylored towards Rails 2: How to enable page caching in a functional test in rails? I want to do something like: test "caching of index method" do with_caching do get :index assert_template 'index' get :index assert_template '' end end Maybe there is also a better way of testing that the cache was hit?
Optionally testing caching in Rails 3 functional tests
Put this code in onDestroy() to clear app cache: void onDestroy() { super.onDestroy(); try { trimCache(this); // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void trimCache(Context context) { try { File dir = context.getCacheDir(); if (dir != null && dir.isDirectory()) { deleteDir(dir); } } catch (Exception e) { // TODO: handle exception } } public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); }
I read through the Android documentation of the cache (see Data Storage Documentation) but I didn't got how I can clean the whole folder. So how can I delete the cache-folder of my app? It's in this path: /Android/data/de.stepforward/cache/
How to delete cache-folder of app?
I found the answer to my question elsewhere on this site. Woot! (Not sure why it didn't appear when I first posted this, but never mind, I got there in the end.) For those interested, the answer was this (as posted by Gabriel McAdams): You do that in IIS. If you are using IIS 7, you can add the header in your web.config. It’s in the system.webServer section. <staticContent> <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" /> </staticContent> This will cause all static content to have an expires HTTP header set to the year 2020. Static content means anything that isn’t served through the ASP.NET engine such as images, script files and styles sheets. Or to use a relative expiration, use this: <staticContent> <clientCache cacheControlMaxAge ="2.00:00:00" cacheControlMode="UseMaxAge" /> </staticContent> This will cause all static content to have an expires HTTP header set to 2 days.
I just ran Google's Page Speed application against our site and one of the recommendations was to Leverage browser caching. Expanding this revealed the following: The following cacheable resources have a short freshness lifetime: Specify an expiration at least one week in the future for the following resources: <a long list of images > <some javascript files > How do I go about lengthening the "freshness lifetime" of particular images? It's an ASP.NET project running on IIS7.5
Asking browsers to cache our images (ASP.NET/IIS)
Here is how I'd solve the problem: 1.- Enable facts gathering on your playbook (site.yml): gather_facts: yes 2.- Enable facts caching on ansible.cfg: 2.1.- Option 1 - Use this if you have the time to install redis: [defaults] gathering = smart fact_caching = redis # two hours timeout fact_caching_timeout = 7200 2.2.- Option 2 - Use this to test right now is simple but slower than redis: [defaults] gathering = smart fact_caching = jsonfile fact_caching_connection = /tmp/facts_cache # two hours timeout fact_caching_timeout = 7200 3.- Update or create the facts cache. To do this create a new role (cache-update) with just one task: execute ping. We use ping because is the simplest and fastest ansible task so it will help us update the cache really fast: - name: Pinging server to update facts cache ping: Greetings,
I am trying to make Ansible work with --limit and to do that I need facts about other hosts, which I am caching with fact_caching. What command should I run so that it simply gathers all the facts on all the hosts and caches them, without running any tasks? Something like the setup module would be perfect if it cached the facts it gathered, but it seems like it does not.
Fastest way to gather facts to fact cache
51 I advise you to use headers mod. You can activate it (if disabled) with this command : a2enmod headers Here is a simple code example that works: <IfModule mod_headers.c> # WEEK <FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch> # WEEK <FilesMatch "\.(js|css|swf)$"> Header set Cache-Control "max-age=604800" </FilesMatch> </IfModule> max-age is cached time in seconds. Share Improve this answer Follow edited Dec 1, 2013 at 23:29 block14 61911 gold badge88 silver badges2626 bronze badges answered Sep 19, 2012 at 15:40 MaraumaxMaraumax 69488 silver badges1616 bronze badges 2 seems that mod_headers.c is turned off. I'll have to send a request to open to the sysadmin. Why is mod_headers.c preffered over mod_expires.c? – Yura Sep 19, 2012 at 15:57 Ok, seem to figure something out... Very strange, but see,s that A3720 means a zero. Thus, if I want an expiration of 10min, I have to wrote 3720+600 i.e 4320. This explains why "A3600" did not work. However, does anyone knows why is the zero line is 3720?!? – Yura Sep 19, 2012 at 16:41 Add a comment  | 
I am trying to configure my .htaccess file to set the cache time. Tryied every possible configuration but nothing works! This is what is written in my HTML: <meta http-equiv="Cache-Control" content="max-age=2592000, public" /> <!-- <meta http-equiv="expires" content="mon, 24 sep 2012 14:30:00 GMT"> --> and this is what written in my .htaccess file: ExpiresActive On ExpiresDefault A3600 However, when I refresh inclusind cache clear (ctrl+F5) in firefox, my firebug NET panel says that the cache expires at the same second I have accessed the file ( and not in the future, as I want it to be). What am I doing wrong?? Thanks
HTTP cache headers with .htaccess
Proceeding with the following steps helped me out: restart the virtual box using: sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart Stop vagrant as follows: vagrant halt start vagrant as follows: vagrant up
I am working with aerospike and installing it using vagrant virtual box. After installation, when i am trying to start the virtual machine, it is giving the following error: . There was an error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below. Command: ["startvm", "dff6693e-52c8-4c9e-922a-243d18c7f666", "--type", "headless"] Stderr: VBoxManage: error: The VM session was closed before any attempt to power it on VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component SessionMachine, interface ISession i am using mac machine for this setup. Any suggestion?
Mac : There was an error while executing `VBoxManage`, a CLI used by Vagrant