Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
51
In the absence of an X-UA-Compatible http-equiv header, the compatibility mode is determined by the !DOCTYPE (or the absence of a !DOCTYPE, as the case may be). For a chart of which !DOCTYPE gives you which mode (in various browsers) see here:
http://hsivonen.iki.fi/doctype/
(You'll need to scroll down toward the bottom of the page.)
You can override this behavior by using a meta element to specify an X-UA-Compatible http-equiv header, like so:
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
(Note: IE=edge goes with the highest available version -- currently IE8 as of this posting -- or one can explicitly specify IE8.)
For more information, see here:
http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
Share
Improve this answer
Follow
edited Jan 25, 2010 at 0:50
answered Jan 20, 2010 at 23:58
Tim GoodmanTim Goodman
23.7k77 gold badges6666 silver badges8585 bronze badges
4
7
Rather than using an aribirarity large number for the IE version, it would be better to use the supported keyword 'edge' to alway force the latest version. <meta http-equiv="X-UA-Compatible" content="IE=edge" >
– Michael Benny
Jan 24, 2010 at 19:50
@mbenny: Good point. I have updated the answer to reflect this.
– Tim Goodman
Jan 25, 2010 at 0:51
12
It's noteworthy that the META tag must come before any SCRIPT tags in the HEAD section.
– xero
Jun 23, 2010 at 17:20
1
You can also specify multiple version like in this example : <meta http-equiv="X-UA-Compatible" content="IE=7,9,10" > See msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx
– Marshall777
Sep 17, 2013 at 8:24
Add a comment
|
|
Just updated my site to newer, much more standards compliant design. My previous design was so rubbish that I had to use the IE=EmulateIE tag to force IE7 emulation.
Unfortunately, I believe that browsers may be caching this setting from previous visits, causing my new site (which looks great without the button pressed) to look rubbish again...
Is there any opposite tag that I could use, or some magic I can make PHP do to the HTTP headers disable caching of this setting?
|
Force IE8 *not* to use Compatibility View
|
You can still use the cache (shared among all responses) and session (unique per user) for storage.
I like the following "try get from cache/create and store" pattern (c#-like pseudocode):
public static class CacheExtensions
{
public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator)
{
var result = cache[key];
if(result == null)
{
result = generator();
cache[key] = result;
}
return (T)result;
}
}
you'd use this like so:
var user = HttpRuntime
.Cache
.GetOrStore<User>(
$"User{_userId}",
() => Repository.GetUser(_userId));
You can adapt this pattern to the Session, ViewState (ugh) or any other cache mechanism. You can also extend the ControllerContext.HttpContext (which I think is one of the wrappers in System.Web.Extensions), or create a new class to do it with some room for mocking the cache.
|
I'd like to cache objects in ASP.NET MVC. I have a BaseController that I want all Controllers to inherit from. In the BaseController there is a User property that will simply grab the User data from the database so that I can use it within the controller, or pass it to the views.
I'd like to cache this information. I'm using this information on every single page so there is no need to go to the database each page request.
I'd like something like:
if(_user is null)
GrabFromDatabase
StuffIntoCache
return CachedObject as User
How do I implement simple caching in ASP.NET MVC?
|
How can I cache objects in ASP.NET MVC?
|
ok here is how to do this if yours is disabled or you need to restore a backup, which seems to disable it.
just run this script, it will kill all the process's that a database is using (why you carnt in 2008 manually kill process's unlike 2005 is beyond me) and then set the broker
USE master
go
DECLARE @dbname sysname
SET @dbname = 'YourDBName'
DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END
ALTER DATABASE @dbname SET ENABLE_BROKER
|
I am integrating SqlCacheDependency to use in my LinqToSQL datacontext.
I am using an extension class for Linq querys found here - http://code.msdn.microsoft.com/linqtosqlcache
I have wired up the code and when I open the page I get this exception -
"The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported. Please enable the Service Broker for this database if you wish to use notifications."
its coming from this event in the global.asax
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
//In Application Start Event
System.Data.SqlClient.SqlDependency.Start(new dataContextDataContext().Connection.ConnectionString);
}
my question is...
how do i enable Service Broker in my SQL server 2008 database? I have tried to run this query.. ALTER DATABASE tablename SET ENABLE_BROKER but it never ends and runs for ever, I have to manually stop it.
once I have this set in SQL server 2008, will it filter down to my DataContext, or do I need to configure something there too ?
thanks for any help
Truegilly
|
Enabling Service Broker in SQL Server 2008
|
67
If you're writing the page dynamically, you can add the last-modified timestamp to the URL:
<img src="image.jpg?lastmod=12345678" ...
Share
Improve this answer
Follow
answered Nov 26, 2008 at 19:28
GregGreg
319k5454 gold badges373373 silver badges336336 bronze badges
3
2
this is the best answer I feel because it still allows the browser to cache.
– Michael St Clair
Feb 15, 2016 at 21:30
5
how about <img src="image.jpg?<?php echo filemtime('image.jpg') ?>", certainly more dynamic!
– luke_mclachlan
Jan 15, 2017 at 22:49
In php normally we can use rand function like that, <img src="image.jpg?new=<?php rand() ?>">
– nafischonchol
Aug 5, 2021 at 17:56
Add a comment
|
|
I know there are many ways to prevent image caching (such as via META tags), as well as a few nice tricks to ensure that the current version of an image is shown with every page load (such as image.jpg?x=timestamp), but is there any way to actually clear or replace an image in the browsers cache so that neither of the methods above are necessary?
As an example, lets say there are 100 images on a page and that these images are named "01.jpg", "02.jpg", "03.jpg", etc. If image "42.jpg" is replaced, is there any way to replace it in the cache so that "42.jpg" will automatically display the new image on successive page loads? I can't use the META tag method, because I need everuthing that ISN"T replaced to remain cached, and I can't use the timestamp method, because I don't want ALL of the images to be reloaded every time the page loads.
I've racked my brain and scoured the Internet for a way to do this (preferrably via javascript), but no luck. Any suggestions?
|
how to clear or replace a cached image
|
The important distinction here is between cache misses caused by the size of your data set, and cache misses caused by the way your cache and data alignment are organized.
Lets assume you have a 32k direct mapped cache, and consider the following 2 cases:
You repeatedly iterate over a 128k array. There's no way the data can fit in that cache, therefore all the misses are capacity ones (except the first access of each line which is a compulsory miss, and would remain even if you could increase your cache infinitely).
You have 2 small 8k arrays, but unfortunately they are both aligned and map to the same sets. This means that while they could theoretically fit in the cache (if you fix your alignment), they will not utilize the full cache size and instead compete for the same group of sets and thrash each other. These are conflict misses, since the data could fit, but still collides due to organization. The same problem can occur with set associative caches, although less often (let's say the cache is 2-way, but you have 4 aligned data sets...).
The 2 types are indeed related, you could say that given high levels of associativity, set skewing, proper data alignments and other techniques, you could reduce the conflicts, until you're mostly left with true capacity misses that are unavoidable.
|
Capacity miss occurs because blocks are being discarded from cache because cache cannot contain all blocks needed for program execution (program working set is much larger than cache capacity).
Conflict miss occurs in the case of set associative or direct mapped block placement strategies, conflict misses occur when several blocks are mapped to the same set or block frame; also called collision misses or interference misses.
Are they actually very closely related?
For example, if all the cache lines are filled and we have a read request for memory B, for which we have to evict memory A.
So should it be considered as a capacity miss since we don't have enough space? And later if we want to access memory A, and since it's evicted before, it's considered as a conflict miss.
Am I understanding this correctly? Thanks
|
What's the difference between conflict miss and capacity miss
|
Maybe your problem is like mine: I have only a few machines for memcached, but with lots of memory. Even if one of them fails or needs to be rebooted, it seriously affects the performance of the system. According to the original memcached philosophy I should add a lot more machines with less memory for each, but that's not cost-efficient and not exactly "green IT" ;)
For our solution, we built an interface layer for the Cache system so that the providers to the underlying cache systems can be nested, like you can do with streams, and wrote a cache provider for memcached as well as our own very simple Key-Value-2-disk storage provider. Then we define a weight for cache items that represent how costly it is to rebuild an item if it cannot be retrieved from cache. The nested Disk cache is only used for items with a weight above a certain threshold, maybe around 10% of all items.
When storing an object in the cache, we won't lose time as saving to one or both caches is queued for asynchronous execution anyway. So writing to the disk cache doesn't need to be fast. Same for reads: First we go for memcached, and only if it's not there and it is a "costly" object, then we check the disk cache (which is by magnitudes slower than memcached, but still so much better then recalculating 30 GB of data after a single machine went down).
This way we get the best from both worlds, without replacing memcached by anything new.
|
I am currently using memcached with my java app, and overall it's working great.
The features of memcached that are most important to me are:
it's fast, since reads and writes are in-memory and don't touch the disk
it's just a key/value store (since that's all my app needs)
it's distributed
it uses memory efficiently by having each object live on exactly one server
it doesn't assume that the objects are from a database (since my objects are not database objects)
However, there is one thing that I'd like to do that memcached can't do. I want to periodically (perhaps once per day) save the cache contents to disk. And I want to be able to restore the cache from the saved disk image.
The disk save does not need to be very complex. If a new key/value is added while the save is taking place, I don't care if it's included in the save or not. And if an existing key/value is modified while the save is taking place, the saved value should be either the old value or the new value, but I don't care which one.
Can anyone recommend another caching solution (either free or commercial) that has all (or a significant percentage) of the memcached features that are important to me, and also allows the ability to save and restore the entire cache from disk?
|
alternative to memcached that can persist to disk
|
As far as syntax goes, you can use the null-coalescing operator if you want to be fancy, but it's not necessarily as readable.
get
{
return notes ?? (notes = CalcNotes());
}
Edit: Updated courtesy of Matthew. Also, I think the other answers are more helpful to the question asker!
|
I have a object with properties that are expensive to compute, so they are only calculated on first access and then cached.
private List<Note> notes;
public List<Note> Notes
{
get
{
if (this.notes == null)
{
this.notes = CalcNotes();
}
return this.notes;
}
}
I wonder, is there a better way to do this? Is it somehow possible to create a Cached Property or something like that in C#?
|
Cached Property: Easier way?
|
You've already written your headers. I don't think you can add more after you've done that, so just put your headers in your first object.
res.writeHead(200, {
'Content-Type': mimeType,
'Content-Length': contents.length,
'Accept-Ranges': 'bytes',
'Cache-Control': 'no-cache'
});
|
I have read that to avoid caching in Node.js, it is necessary to use:
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
But I don't know how to use it because I get errors when I put that line in my code.
My function (where I think I have to program the Cache-Control header) is:
function getFile(localPath, mimeType, res) {
fs.readFile(localPath, function(err, contents) {
if (!err) {
res.writeHead(200, {
"Content-Type": mimeType,
"Content-Length": contents.length,
"Accept-Ranges": "bytes",
});
// res.header('Cache-Control', 'no-cache');
res.end(contents);
} else {
res.writeHead(500);
res.end();
}
});
}
Does anyone know how to put no cache in my code?
|
No cache in Node.js server
|
Yes, this is a current issue in Chrome. There is an issue report here.
The fix will appear in 40.x.y.z versions.
Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.
|
Does anybody know what the following Chrome error is?
Failed to load resource: net::ERR_CACHE_MISS
I have had a look online, but have not found a good answer yet. Somebody said it might be related to the latest Chrome update?
What is it and how can I resolve the issue?
Cheers
|
Chrome - ERR_CACHE_MISS
|
There is no such thing in .Net Core yet.
Here is my workaround:
var field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance);
var collection = field.GetValue(_memoryCache) as ICollection;
var items = new List<string>();
if (collection != null)
foreach (var item in collection)
{
var methodInfo = item.GetType().GetProperty("Key");
var val = methodInfo.GetValue(item);
items.Add(val.ToString());
}
|
To be succinct. Is possible list all register keys from Memory Cache in the .Net Core Web Application?
I didn't find anything in IMemoryCache interface.
|
How to retrieve a list of Memory Cache keys in asp.net core?
|
Spark 2.x
You can use Catalog.clearCache:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate
...
spark.catalog.clearCache()
Spark 1.x
You can use SQLContext.clearCache method which
Removes all cached tables from the in-memory cache.
from pyspark.sql import SQLContext
from pyspark import SparkContext
sqlContext = SQLContext.getOrCreate(SparkContext.getOrCreate())
...
sqlContext.clearCache()
|
I am a spark application with several points where I would like to persist the current state. This is usually after a large step, or caching a state that I would like to use multiple times. It appears that when I call cache on my dataframe a second time, a new copy is cached to memory. In my application, this leads to memory issues when scaling up. Even though, a given dataframe is a maximum of about 100 MB in my current tests, the cumulative size of the intermediate results grows beyond the alloted memory on the executor. See below for a small example that shows this behavior.
cache_test.py:
from pyspark import SparkContext, HiveContext
spark_context = SparkContext(appName='cache_test')
hive_context = HiveContext(spark_context)
df = (hive_context.read
.format('com.databricks.spark.csv')
.load('simple_data.csv')
)
df.cache()
df.show()
df = df.withColumn('C1+C2', df['C1'] + df['C2'])
df.cache()
df.show()
spark_context.stop()
simple_data.csv:
1,2,3
4,5,6
7,8,9
Looking at the application UI, there is a copy of the original dataframe, in adition to the one with the new column. I can remove the original copy by calling df.unpersist() before the withColumn line. Is this the recommended way to remove cached intermediate result (i.e. call unpersist before every cache()).
Also, is it possible to purge all cached objects. In my application, there are natural breakpoints where I can simply purge all memory, and move on to the next file. I would like to do this without creating a new spark application for each input file.
Thank you in advance!
|
Un-persisting all dataframes in (py)spark
|
Found it:
I need to specify client cache for static content (in web.config).
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public"
cacheControlMaxAge="12:00:00" cacheControlMode="UseMaxAge" />
</staticContent>
</system.webServer>
</configuration>
from http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache
|
I am already using output caching in my ASP.NET MVC application.
Page speed tells me to specify HTTP cache expiration for css and images in the response header.
I know that the Response object contains some properties that control cache expiration. I know that these properties can be used to control HTTP caching for response that I am serving from my code:
Response.Expires
Response.ExpiresAbsolute
Response.CacheControl
or alternatively
Response.AddHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
The question is how do I set the Expires header for resources that are served automatically, e.g. images, css and such?
|
How to specify HTTP expiration header? (ASP.NET MVC+IIS)
|
21
You could try cachegrind and it's front-end kcachegrind.
Share
Improve this answer
Follow
answered Mar 21, 2010 at 11:53
TaaviTaavi
32122 silver badges33 bronze badges
0
Add a comment
|
|
I know that I can use gprof to benchmark my code.
However, I have this problem -- I have a smart pointer that has an extra level of indirection (think of it as a proxy object).
As a result, I have this extra layer that effects pretty much all functions, and screws with caching.
Is there a way to measure the time my CPU wastes due to cache misses?
|
Linux C++: how to profile time wasted due to cache misses?
|
Assuming you don't want to modify the code (e.g., because you want to be able to just port to 3.3 and use the stdlib functools.lru_cache, or use functools32 out of PyPI instead of copying and pasting a recipe into your code), there's one obvious solution: Create a new decorated instance method with each instance.
class Test:
def cached_method(self, x):
return x + 5
def __init__(self):
self.cached_method = lru_cache(maxsize=16)(self.cached_method)
|
Using the LRU Cache decorator found here:
http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/
from lru_cache import lru_cache
class Test:
@lru_cache(maxsize=16)
def cached_method(self, x):
return x + 5
I can create a decorated class method with this but it ends up creating a global cache that applies to all instances of class Test. However, my intent was to create a per instance cache. So if I were to instantiate 3 Tests, I would have 3 LRU caches rather than 1 LRU cache that for all 3 instances.
The only indication I have that this is happening is when calling the cache_info() on the different class instances decorated methods, they all return the same cache statistics (which is extremely unlikely to occur given they are being interacted with very different arguments):
CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)
CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)
CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)
Is there a decorator or trick that would allow me to easily cause this decorator to create a cache for each class instance?
|
Python LRU Cache Decorator Per Instance
|
I am currently using django-redis as cache backend for Redis. I haven't used django-redis-cache so far, but what made me take the decision to use django-redis are the following:
Modular client system (pluggable clients).
Some of the pluggable clients come out of the box (shard client, herd client, etc.)
Master-Slave support in the default client.
Facilities for raw access to Redis client/connection pool (very useful).
Better documented.
On django-redis documentation site, you can find more reasons to consider it. What I can tell from my experience so far is that I am very happy with django-redis.
|
I noticed that there are two different projects for using redis for django cache
https://github.com/sebleier/django-redis-cache/
https://github.com/niwibe/django-redis
Is one better known than the other, more of a standard package? I can't decide which to use.
|
Difference between django-redis-cache and django-redis for redis caching with Django?
|
0
There is no terminating condition in your loop so it's going to run forever and cause the memory issue you mentioned. You should add a relevant break condition in your loop and test if it resolves the issue.
def loop_bucket_gets
bucket = Couchbase::Bucket.new({:node_list => ['xxx.xxx.xxx.xxx:8091', 'yyy.yyy.yyy.yyy:8091'],
:bucket => 'Foo',
:pool => 'default',
:expires_in => 1.day,
:default_format => :marshal,
:key_prefix => '_foo'
})
i = 0
loop do
begin
i += 1
bucket.get "ABC#{i}"
break if YOUR_TERMINATING_CONDITION
rescue ::Couchbase::Error::Base => e
nil
end
end
end
Share
Improve this answer
Follow
answered Feb 27, 2023 at 11:03
Sachin SinghSachin Singh
1,03388 silver badges1717 bronze badges
Add a comment
|
|
I have the following test code:
def loop_bucket_gets
bucket = Couchbase::Bucket.new({:node_list => ['xxx.xxx.xxx.xxx:8091', 'yyy.yyy.yyy.yyy:8091'],
:bucket => 'Foo',
:pool => 'default',
:expires_in => 1.day,
:default_format => :marshal,
:key_prefix => '_foo'
})
i = 0
loop do
begin
i += 1
bucket.get "ABC#{i}"
rescue ::Couchbase::Error::Base => e
nil
end
end
end
When I execute this in the Rails console the memory leaks.
I'm using:
couchbase 1.3.10 gem
libcouchbase 2.4.3
I created an issue at https://www.couchbase.com/issues/browse/RCBC-187
|
How to find and fix a Rails and Couchbase memory leak
|
You can support multiple frontend domains this way:
backend example1 {
.host = "backend.example1.com";
.port = "8080";
}
backend example2 {
.host = "backend.example2.com";
.port = "8080";
}
sub vcl_recv {
if (req.http.host == "example1.com") {
#You will need the following line only if your backend has multiple virtual host names
set req.http.host = "backend.example1.com";
set req.backend = example1;
return (lookup);
}
if (req.http.host == "example2.com") {
#You will need the following line only if your backend has multiple virtual host names
set req.http.host = "backend.example2.com";
set req.backend = example2;
return (lookup);
}
}
|
We have a server which needs to serve multiple domains though varnish e.g. example1.com, example2.com and example3.com
Our current .vcl file looks like this:
sub vcl_recv {
set req.http.Host = "example1.com";
lookup;
}
How do I set the correct req.http.Host for the correct incoming request?
|
Configure multiple sites with Varnish
|
The inelegant way is to simply add a call to res.set() prior to any JSON output. There, you can specify to set the cache control header and it will cache accordingly.
res.set('Cache-Control', 'public, max-age=31557600'); // one year
Another approach is to simply set a res property to your JSON response in a route then use fallback middleware (prior to the error handling) to render and send the JSON.
app.get('/something.json', function (req, res, next) {
res.JSONResponse = { 'hello': 'world' };
next(); // important!
});
// ...
// Before your error handling middleware:
app.use(function (req, res, next) {
if (! ('JSONResponse' in res) ) {
return next();
}
res.set('Cache-Control', 'public, max-age=31557600');
res.json(res.JSONResponse);
})
Edit: Changed from res.setHeader to res.set for Express v4
|
How it is possible to set up a cache-control policy in express.js on JSON response?
My JSON response doesn't change at all, so I want to cache it aggressively.
I found how to do caching on static files but can't find how to make it on dynamic data.
|
Cache Control for Dynamic Data Express.JS
|
You may pass a version string as a get parameter to the URL of your script tag. The parameter won't be evaluated by the static JavaScript file but force the browser to get the new version.
If you do not want to assign the version string every time you edited the source you may compute it based on the file system time stamp or your subversion commit number:
<script src="/script.js?time_stamp=1224147832156" type="text/javascript"></script>
<script src="/script.js?svn_version=678" type="text/javascript"></script>
|
I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).
I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.
I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.
I imagine this would be independent for each browser, but I'm not sure.
I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.
|
When does browser automatically clear cache of external JavaScript file?
|
If you don't need some kind of expiration logic, I would suggest using concurrent collections. You can easily implement a single entry caching mechanism combining ConcurrentDictionary and Lazy classes. Here is another link about Lazy and ConcurrentDictionary combination.
If you need your items to expire, then you better use the built-in MemoryCache and implement double-checked locking pattern to guarantee single retrieval of cache items. A ready to go implementation of double checked locking can be found in Locking pattern for proper use of .NET MemoryCache
|
I am looking to implement caching at a request level for a WCF Service. Each request to this service performs a large number of database calls. Think multiple data collectors. We need to allow one data collector to access the information already retrieved by a preceding data collector.
I was looking to use the new .Net 4.0 Memory cache for this by creating a specific instance per request.
Is this a good idea ? Or should I simply use a Dictionary object ?
BTW : The data collection is going to be in parallel, so there will be more complexities around locking but I could use concurrent collections for that as well.
|
Memory Cache or Concurrent Dictionary?
|
Maybe shelve? It's basically a key-value store where you can store python objects. http://docs.python.org/library/shelve.html
Or maybe you could just use the filesystem?
|
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
Short Question:
Is there any nosql flat-file database available as sqlite?
Explanation:
Flat file database can be opened in different processes to read, and keep one process to write. I think its perfect for read cache if there's no strict consistent needed. Say 1-2 secs write to the file or even memory block and the readers get updated data after that.
So I almost choose to use sqlite, as my python server read cache. But there's still one problem. I don't like to rewrite sqls again in another place and construct another copy of my data tables in sqlite just as the same as I did in PostgreSql which used as back-end database.
so is there any other choice?thanks!
|
Is there any nosql flat file database just as sqlite? [closed]
|
For Symfony 3+:
php bin/console
will list all commands, the following are relevant for cache:
php bin/console doctrine:cache:clear-metadata
php bin/console doctrine:cache:clear-query
php bin/console doctrine:cache:clear-result
Before Symfony 3:
app/console
will list how you can do it
app/console doctrine:cache:clear-metadata
app/console doctrine:cache:clear-query
app/console doctrine:cache:clear-result
|
I need to clear my doctrine's cache in Symfony.
There must be some way in command line for clear the cache.
Or where should I find and delete the files belonging to cache?
|
Symfony: Clear doctrine cache
|
I had a look at the source code. It processes the setImageWithURL method like this:
Ask the memory cache if the image is there, if yes return the image and don't go any further
Ask the disk cache if the image is there, if yes return the image and don't go any further
Try to download the image, return image on success else keep the placeholder image
There is no request sent to ask the remote server if there is a new version while there is something old on disk, like using ETags of the HTTP protocol.
Digging a bit deeper the cache time is set to a static value in SDImageCache.m
static NSInteger cacheMaxCacheAge = 60*60*24*7; // 1 week
it cannot be changed with a setter.
So as long as the image in the cache is valid the SDWebImage lib won't download anything new. After a week it'll download your changed image.
|
I am using the SDWebImage library to cache web images in my app:
https://github.com/rs/SDWebImage/blob/master/README.md
Current Usage:
[imageView setImageWithURL:[NSURL URLWithString:profilePictureUrl] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
My question is what happens once the image has been cached and then a couple of days later that image file on the server has been updated with a new image?
At the moment my application is still displaying the cached image.
I can't see in any of the documentation on setting a cache timeout or something that recognises that the file size has changed.
If anyone has experience using this particular library then any help would be greatly appreciated.
Thanks in advance.
|
What happens to SDWebImage Cached Images in my app when the image file on the server changes?
|
Add:
before(:all) do
Rails.cache.clear
end
to have the cache cleared before each spec file is run.
Add:
before(:each) do
Rails.cache.clear
end
to have the cache cleared before each spec.
You can put this inside spec/spec_helper.rb within the RSpec.configure block to have it applied globally (recommended over scattering it per spec file or case).
RSpec by default does not clear that cache automatically.
|
We cache id/path mapping using Rails.cache in a Rails 3.2 app. On some machines it works OK, but on the others values are wrong. The cause is hard to track so I have some questions about the Rails.cache itself. Is it purged between tests? Is it possible that values cached in development mode is used in test mode? If it's not purged, how could I do it before running specs?
My cache store is configuration is:
#in: config/environments/development.rb
config.cache_store = :memory_store, {:size => 64.megabytes}
#in: config/environments/production.rb
# config.cache_store = :mem_cache_store
|
is Rails.cache purged between tests?
|
I would handle it in the repository/data access layer. The reasoning is because it isn't up to the business layer on where to get the data from, that is the job of the repository. The repository will then decide where to get the data from, the cache (if it's not too old) or from the live data source based on the circumstances of the data access logic.
It's a data access concern more than a business logic issue.
|
I'm not sure where I should implement the caching in my repository pattern.
Should I implement it in the service-logic or in the repository?
GUI -> BusinessLogic (Services) -> DataAccess (Repositories)
|
Repository Pattern - Caching
|
Unfortunately, I found this link which appears to indicate that we cannot cache these locally, therefore making this question moot.
http://support.google.com/enterprise/doc/gme/terms/maps_purchase_agreement.html
4.4 Cache Restrictions. Customer may not pre-fetch, retrieve, cache, index, or store any Content, or portion of the Services with the exception being Customer may store limited amounts of Content solely to improve the performance of the Customer Implementation due to network latency, and only if Customer does so temporarily, securely, and in a manner that (a) does not permit use of the Content outside of the Services; (b) is session-based only (once the browser is closed, any additional storage is prohibited); (c) does not manipulate or aggregate any Content or portion of the Services; (d) does not prevent Google from accurately tracking Page Views; and (e) does not modify or adjust attribution in any way.
So it appears we cannot use Google map tiles offline, legally.
|
Like Nokia's OVI maps can be used offline, there must be some way of caching Google map tiles too. Any hints?
|
How to cache Google map tiles for offline usage?
|
32
CDN (Content Delivery Network) adds X-cache header to HTTP Response. X-cache:HIT means that your request was served by CDN, not origin servers. CDN is a special network designed to cache content, so that usr request served faster + to unload origin servers.
Share
Improve this answer
Follow
answered Apr 21, 2015 at 12:18
Yuriy VasylenkoYuriy Vasylenko
3,1012626 silver badges2626 bronze badges
1
1
Furthermore, there are a bunch of "X- " headers provided by CDNs. They indicate HIT, MISS etc. You can simply install firebug plugin in firefox and request some progressive download video, probably it'll be served by cdn node, so the HOST header in response might contain smth like cdn.rt.com and there will be "X- " headers
– Yuriy Vasylenko
Apr 21, 2015 at 12:26
Add a comment
|
|
I was going through the firefox local cache folder and found a lot of files containing the X-cache header. Can someone explain the purpose of this header ?
thanks
|
X-Cache Header Explanation
|
According to the JPA 2.0 specification, if you want to selectively cache entities using the @Cacheable annotation, you're supposed to specify a <shared-cache-mode> in the persistence.xml (or the equivalent javax.persistence.sharedCache.mode when creating the EntityManagerFactory).
Below, a sample persistence.xml with the relevant element and properties:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="FooPu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
...
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
...
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.SingletonEhCacheProvider"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
</properties>
</persistence-unit>
</persistence>
Note that I've seen at least one issue HHH-5303 related to caching. So the above is not guaranteed :)
References
Hibernate EntityManager reference guide
2.2.1 Packaging
JPA 2.0 Specification
Section 3.7.1 "The shared-cache-mode Element"
Section 11.1.7 "Cacheable Annotation"
|
Typically , I use Hibernate's @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) to cache an @Entity class , and it works well.
In JPA2 , there's another @Cacheable annotation that seems to be the same functionality with Hibernate's @Cache. To make my entity class independent of hibernate's package , I want to give it a try. But I cannot make it work. Each time a simple id query still hits the DB.
Can anybody tell me where goes wrong ? Thanks.
Entity class :
@Entity
//@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Cacheable(true)
public class User implements Serializable
{
// properties
}
Test class :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:app.xml"})
@TransactionConfiguration(transactionManager="transactionManager")
public class UserCacheTest
{
@Inject protected UserDao userDao;
@Transactional
@Test
public void testGet1()
{
assertNotNull(userDao.get(2L));
}
@Transactional
@Test
public void testGet2()
{
assertNotNull(userDao.get(2L));
}
@Transactional
@Test
public void testGet3()
{
assertNotNull(userDao.get(2L));
}
}
The test result shows each "get" hits DB layer (with hibernate.show_sql=true).
Persistence.xml :
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_outer_join" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.SingletonEhCacheProvider"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
JPA code :
@Override
public T get(Serializable id)
{
return em.find(clazz, id);
}
|
How to use JPA2's @Cacheable instead of Hibernate's @Cache
|
I can confirm that this is indeed a bug. The quick description of what's going wrong here is as follows: In CallBaz, there is a single callsite that is invoked three times. That callsite is an InvokeMember, because that's the best guess the compiler can make given the C# syntax, despite that it could, in actuality, resolve to a GetMember followed by an Invoke.
During the second execution of the callsite, this is indeed the binding that the runtime finds. And so it produces a deferral to a GetMember followed by an invoke. The bug is that this deferral does not properly restrict itself to the case where the argument is the anonymous type. Therefore, in the third execution the deferral kicks in and the GetMember tries to bind to Program, which of course fails.
Thanks for finding this. As Eric points out, we're in a very late stage here, and it's becoming difficult to fix issues before we ship. But we also want to ship the right product. I'm going to do what I can to get this resolved, though I may not succeed. If you come up with anything else, please feel free to contact me. =)
UPDATE:
Although I can make no guarantee what the final version of VS 2010 and C# 4 will look like when it ships, I can say that I was successful in pushing this fix through. Today's release escrow build behaves correctly for your code. Barring some catastrophe, you will see this fixed at release. Thanks again. I owe you a beer.
|
There is some strange behavior with the C# 4.0 dynamic usage:
using System;
class Program {
public void Baz() { Console.WriteLine("Baz1"); }
static void CallBaz(dynamic x) { x.Baz(); }
static void Main(string[] args) {
dynamic a = new Program();
dynamic b = new { Baz = new Action(() => Console.WriteLine("Baz2")) };
CallBaz(a); // ok
CallBaz(b); // ok
CallBaz(a); // Unhandled Exception:
// Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
// The name 'Baz' is bound to a method and cannot be used like a property
}
}
I'm using the Visual Studio 2010 Release Candidate.
Is this a bug? If it's true, will it be fixed in the Release?
|
Is something wrong with the dynamic keyword in C# 4.0?
|
Page metadata isn't the sort of thing that should change very often, but you can manually clear the cache by going to Facebook's Debug Tool and entering the URL you want to scrape
There's also an API for doing this, which works for any OG object:
curl -X POST \
-F "id={object-url OR object-id}" \
-F "scrape=true" \
-F "access_token={your access token}" \
"https://graph.facebook.com"
An access_token is now required. This can be an app or page access_token; no user authentication is required.
|
I'm aware you can force update a page's cache by entering the URL on Facebook's debugger tool while been logged in as admin for that app/page:
https://developers.facebook.com/tools/debug
But what I need is a way to automatically call an API endpoint or something from our internal app whenever somebody from our Sales department updates the main image of one of our pages. It is not an option to ask thousands of sales people to login as an admin and manually update a page's cache whenever they update one of our item's description or image.
We can't afford to wait 24 hours for Facebook to update its cache because we're getting daily complaints from our clients whenever they don't see a change showing up as soon as we change it on our side.
|
Is there an API to force Facebook to scrape a page again?
|
You could take a Map as cache and take nested maps for all following arguments.
This cache works for arbitrary count of arguments and reuses the values from the former calls.
It works by taking a curried function and an optional Map. If the map is not supplied, a new map is created which serves as base cache for all other calls of the returned closure or the final result.
The inner function takes a single argument and checks if this value is in the map.
If not, call the curried function and check the returned value
if function, create a new closure over the function and a new map,
if no function take the result,
as value for a new element of the map.
Finally return the value from the map.
const cached = (fn, map = new Map()) => arg => {
const inCache = map.has(arg);
const hint = inCache ? 'in cache' : 'not in cache';
console.log(arg, hint);
if (!inCache) {
const value = fn(arg);
const result = typeof value === 'function' ? cached(value, new Map()) : value;
map.set(arg, result);
}
return map.get(arg);
};
const f = a => b => c => a * b * c; // the original curried function
const g = cached(f); // its cached variant
console.log(g(1)(2)(5)); // not not not 10
console.log(g(1)(3)(4)); // in not not 12
console.log(g(4)(2)(3)); // not not not 24
console.log(g(1)(2)(6)); // in in not 12
console.log(g(4)(2)(3)); // in in in 24
.as-console-wrapper { max-height: 100% !important; top: 0; }
|
const f = (arg1) => (arg2) => { /* returns something */ }
Is it possible to memoize f with regard to the 2 arguments, namely:
f(1)(2);
f(1)(3); // Cache not hit
f(4)(2); // Cache not hit
f(1)(2); // Cache hit
|
Memoize a curried function
|
Don't use these:
viewer.getSettings().setAppCacheMaxSize(1024*1024*8);
viewer.getSettings().setAppCachePath("/data/data/com.your.package.appname/cache");
viewer.getSettings().setAppCacheEnabled(true);
These have nothing to do with the default webview internal cache. Appcache is an entirely different feature mean to make you able to run the website w/o an internet connection. It does not work that great and probably you do not want to use it.
With setting this: viewer.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT) is enough.
|
Which one is faster way to load mobile web pages and non mobile web pages in Android webview; loading cache or not loading that at all?
And what is recommend style to load that?
Right now when I don't load cache at all non mobile sites are much more slower to load than when I load them in native browser.
|
Caching in Android webview
|
8
Can this be done in IIS 6?
To configure content expiration
In the Internet Information Services (IIS) Manager administrative tool, right-click Your Web Site, and then click Properties.
In the Properties dialog box, on the HTTP Headers tab specify expiration time, and then click OK.
Share
Improve this answer
Follow
answered Aug 13, 2009 at 9:55
VladislavVladislav
1,79711 gold badge3030 silver badges3939 bronze badges
1
8
Does this affect only static content such as images / style sheets? I don't want IIS to tell the browser to cache aspx pages that get updated frequently.
– Code Commander
Mar 1, 2011 at 17:27
Add a comment
|
|
After running the YSlow plugin on a site, I saw that one of the recommendations was to add far future expires headers to the scripts, stylesheets, and images.
I would like to do this, does anyone have experience with this? I am using IIS 7 and I read an article from Microsoft but am not interested in disabling caching for asp pages or images, I actually want to force caching for static content. Also, the ideal situation would not exist in code, but in the web server configuration.
So, what steps would I have to take to have every image, javascript file, and stylesheet to be cached?
|
Add Expires or Cache Control Header to static content in IIS
|
Imagine you were looking up the details of buses as they arrived at a bus stop, based on their bus number (or whatever identifier you use).
It's somewhat reasonable to think that if you've just seen a number 36 bus, you're less likely to see another one imminently than to see one of the other buses that stops there.
Just one example, but the idea is more general: in some cases, having "just seen something" is a good indicator that you're unlikely to see the same thing again soon.
|
I know the algorithms of MRU and its reversed one Least Recently Used (LRU).
I think LRU is reasonable, as LRU element means it will be used at least possible in future. However, MRU element means the element is very possible to be used in future, why evict it? What is the reasonable scenario?
|
Why does cache use Most Recently Used (MRU) algorithm as evict policy?
|
I figured it out. Had to update the firebase.json file according to this Github comment:
{
"hosting": {
"headers": [
{ "source":"/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}] }
]
}
}
|
I have a site built with create-react-app and hosted on Firebase Hosting. What can I do to specify the browser cache needs to be updated after new deploys, and ideally only for pages, assets, and stylesheets that have been changed since the last deploy?
Is there a way to access the deploy id and include that (or any other unique identifier) in the headers so the browser can compare to what it has in local storage or cache and determine whether a hard refresh is necessary? I looked over the Firebase Deploying as well as Full config docs but there's no mention on how to access hosting metadata like the last deploy time.
Setting a Cache-Control value to max-age=[any number] doesn't seem ideal because it disregards when the next deployment will occur (which might be unknown to begin with unless there are regular schedules).
|
Firebase hosting - force browser to reset cache on new deploys?
|
48
I had the same problem and changing (incrementing) the version number in package.json before running the build command fixed it.
For example by default the version number is set to "0.1.0"
package.json file:
{
"name": "project-name",
"version": "0.1.1",
"private": true,
...
}
Share
Improve this answer
Follow
edited May 19, 2022 at 13:21
answered Nov 8, 2020 at 22:24
Delphin RUKUNDODelphin RUKUNDO
62366 silver badges88 bronze badges
2
4
This is better way for force cache update.
– Ish
Jun 10, 2021 at 20:48
after run npm run build only change on package json there is no need to commit into git , did u know why ? its really integrate to command npm run build ? i have already push my dist from version 0.1.1 then change into 1.1.1 then run npm run build, but there is no need to commit or push . i think we need to npm install first, right ???
– Yogi Arif Widodo
Aug 25, 2022 at 21:38
Add a comment
|
|
I created an app with vue-cli and then I build the dist folder for production.
The app is deployed on IIS with flask backend and works fine.
The problem occurs when I have to make some changes and I have to redo the deployment. After this, users call me because app doesn't work but if I clear the chrome cache, the app works fine again.
How can I fix this problem? Is there a method to clear chrome cache automatically when I release a new application version?
Thanks
my dist folder
deployment: copy and paste folder dist on IIS
if files in dist folder are correct, maybe the problem is in axios cache? i have make some changes also to rest apis
|
how to force clearing cache in chrome when release new Vue app version
|
The easiest way would be to handle caching in your repository provider. That way you don't have to change out any code in the rest of your app; it will be oblivious to the fact that the data was served out of a cache rather than the repository.
So, I'd create an interface that the controllers use to communicate with the backend, and in the implementation of this I'd add the caching logic. Wrap it all up in a nice bow with some DI, and your app will be set for easy testing.
|
I have an MVC-based site, which is using a Repository/Service pattern for data access.
The Services are written to be using in a majority of applications (console, winform, and web). Currently, the controllers communicate directly to the services. This has limited the ability to apply proper caching.
I see my options as the following:
Write a wrapper for the web app, which implements the IWhatEverService which does caching.
Apply caching in each controller by cache the ViewData for each Action.
Don't worry about data caching and just implement OutputCaching for each Action.
I can see the pros and cons of each. What is/should the best practice be for caching with Repository/Service
|
Caching Data Objects when using Repository/Service Pattern and MVC
|
I think you nailed the two compelling reasons :-)
The MemoryCache has an eviction strategy, so that it can throw out entries that are no longer needed or for that you do not have enough memory anymore.
A Dictionary will not "lose contents".
Update: MemoryCache is thread-safe and has methods such as AddOrGetExisting. With a Dictionary, you'd have to synchronize access yourself (or use ConcurrentDictionary).
|
I have just come across the MemoryCache which is new in .NET 4.
I get that it can be useful if you want to:
Limit the total memory usage of the cache
Have an object expiry time (time to live) for objects you put in the cache
Are there any other compelling reasons to use a MemoryCache over a standard Dictionary<string,object>
I have a few books on C# and .NET and there is no reference to it anywhere.
|
What are the compelling reasons to use a MemoryCache over a plain old Dictionary<string,object>
|
What @emcas88 is trying to say is that EF will only check the cache when you use the .Find method on DbSet.
Using .Single, .First, .Where, etc will not cache the results unless you are using second-level caching.
|
Perhaps I am misunderstanding the caching that DbContext and DbSet does but I was under the impression that there was some caching that would go on. I'm seeing behavior that I wouldn't expect when I run the following code:
var ctx = CreateAContext();
var sampleEntityId = ctx.SampleEntities.Select(i => i.Id)
.Single(i => i == 3); //Calls DB as expected
var cachedEntityId = ctx.SampleEntities.Select(i => i.Id)
.Single(i => i == 3); //Calls DB unexpectedly
What's going on here? I thought that part of what you get from DbSet is that it would first check the local cache to see if that object exists before querying the database. Is there just some sort of configuration option I am missing here?
|
Why does Entity Framework 6.x not cache results?
|
OK, apparently no-cache was not enough.
The following does the trick:
<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
|
how can I force a browser to always load the newest version of index.htm when the page is loaded by entering the URL www.mydomain.com/index.htm or just www.mydomain.com in the browser's address field and pressing enter.
I'm trying this in Chrome and the newest version of index.htm is apparently only loaded, when I refresh manually (F5), or when the URL is already in the browser's address field and I press enter.
I guess I am doing something extremely stupid, because when I searched for the issue, all I could find were solutions about how to make a browser reload your .js and .css files by appending ?v=xxxx to the file names. But how should this work, if not even the newest version of index.htm page, in which I am doing these modifiactions, is loaded??
I also tried putting
<meta http-equiv="cache-control" content="no-cache">
in the <head> of index.htm. But this does not seem to have any effect.
Any help would be greatly appreciated!
Thanks, Linus
|
Force browser to reload index.htm
|
Leverage browser caching:
Setting an expiry date or a maximum
age in the HTTP headers for static
resources instructs the browser to
load previously downloaded resources
from local disk rather than over the
network.
http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching
To set an expiry date or a maximum age in the HTTP headers for static resources
Open IIS manager-> Click your site-> Click the HTTP Response Headers in the home page-> Click the Set Common Headers on the Actions panel -> Check Expire Web Content -> Set After 7 days (as suggested for in the page speed analysis "Specify an expiration at least one week in the future for the following resources"
http://technet.microsoft.com/en-us/library/cc770661%28WS.10%29.aspx
|
I am using IIS 6 and IIS 7 as a web server.
After running Google page speed online , it remarks that I should be: Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.
And it lists a lot of plain images , my javascript files and the style sheets.
How can I set this expiry date for these static files ? I thought this was done automatically by the browser ?
|
How do you set the expiry date or a maximum age in the HTTP headers for static resources in IIS
|
Go to Internet Options. On the General tab, under Browsing History click Settings. Select the "Every time I visit the webpage" radio button.
This doesn't "disable" the cache per se, but it should fix your underlying problem - the JS files should be reloaded every time.
|
How can I disable cache in IE8 ?
We are doing Javascript development and testing it in IE8, but we have to clear the cache every time we make changes to the Javascript files.
|
How to disable cache in InternetExplorer 8
|
Just do pip install python-memcached and you should be good.
As for installing memcached itself, it depends on the platform you are on.
Windows - http://pureform.wordpress.com/2008/01/10/installing-memcache-on-windows-for-php/
OS X - brew install memcached
Debian/Ubuntu - sudo apt-get install memcached
On OS X/Linux, just run memcached in the command line.
|
From the django docs:
After installing Memcached itself, you'll need to install a memcached binding. There are several python memcached bindings available; the two most common are python-memcached and pylibmc.
The pylibmc docs have their own requirements:
-libmemcached 0.32 or later (last test with 0.51)
-zlib (required for compression support)
-libsasl2 (required for authentication support)
So it seems to me that I need to do the following:
-install memcached
-install libmemcached
-install zlib
-install libsas12
-install pylibmc
How/where can I do this? I've been used to just pip installing whatever I need but I can't even tell which of these are python packages. Are these bundled together anywhere?
|
Installing memcached for a django project
|
You should not call dispose on the Default member of the MemoryCache if you want to be able to use it anymore:
The state of the cache is set to indicate that the cache is disposed.
Any attempt to call public caching methods that change the state of
the cache, such as methods that add, remove, or retrieve cache
entries, might cause unexpected behavior. For example, if you call the
Set method after the cache is disposed, a no-op error occurs. If you
attempt to retrieve items from the cache, the Get method will always
return Nothing.
http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.dispose.aspx
About the Trim, it's supposed to work:
The Trim property first removes entries that have exceeded either an absolute or sliding expiration. Any callbacks that are registered
for items that are removed will be passed a removed reason of Expired.
If removing expired entries is insufficient to reach the specified trim percentage, additional entries will be removed from the cache
based on a least-recently used (LRU) algorithm until the requested
trim percentage is reached.
But two other users reported it doesnt work on same page so I guess you are stuck with Remove() http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.trim.aspx
Update
However I see no mention of it being singleton or otherwise unsafe to have multiple instances so you should be able to overwrite your reference.
But if you need to free the memory from the Default instance you will have to clear it manually or destroy it permanently via dispose (rendering it unusable).
Based on your question you could make your own singleton-imposing class returning a Memorycache you may internally dispose at will.. Being the nature of a cache :-)
|
I use a System.Runtime.Caching.MemoryCache to hold items which never expire. However, at times I need the ability to clear the entire cache. How do I do that?
I asked a similar question here concerning whether I could enumerate the cache, but that is a bad idea as it needs to be synchronised during enumeration.
I've tried using .Trim(100) but that doesn't work at all.
I've tried getting a list of all the keys via Linq, but then I'm back where I started because evicting items one-by-one can easily lead to race conditions.
I thought to store all the keys, and then issue a .Remove(key) for each one, but there is an implied race condition there too, so I'd need to lock access to the list of keys, and things get messy again.
I then thought that I should be able to call .Dispose() on the entire cache, but I'm not sure if this is the best approach, due to the way it's implemented.
Using ChangeMonitors is not an option for my design, and is unnecassarily complex for such a trivial requirement.
So, how do I completely clear the cache?
|
How do I clear a System.Runtime.Caching.MemoryCache
|
A quick test seems to show that these settings are only loaded at application startup.
//edit the config file now.
Console.ReadLine();
Console.WriteLine(ConfigurationManager.AppSettings["ApplicationName"].ToString());
Console.WriteLine("Press enter to redisplay");
//edit the config file again now.
Console.ReadLine();
Console.WriteLine(ConfigurationManager.AppSettings["ApplicationName"].ToString());
Console.ReadLine();
You'll see that all outputs remain the same.
|
We know that IIS caches ConfigurationManager.AppSettings so it reads the disk only once until the web.config is changed. This is done for performance purposes.
Someone at:
http://forums.asp.net/p/1080926/1598469.aspx#1598469
stated that .NET Framework doesn't do the same for app.config, but it reads from the disk for every request. But I find it hard to believe, 'cause it would be slower. Please tell me that he is wrong or I'll have to fix every Console/Windows Forms/Windows Services I wrote.
Update I regret that I misinterpreted what people said in the linked forum above.
|
ConfigurationManager.AppSettings Caching
|
Microsoft recommends using System.Runtime.Caching for all caching purposes. See this: http://msdn.microsoft.com/en-us/library/dd997357.aspx
Although, I have come across a couple threads where people are having issues with the MemoryCache.Default instance. After a while, it stops working properly. Any item you add using the Add or Set method does not actually get added to the cache. I tried the same and was able to reproduce this issue with explicitly calling MemoryCache.Default.Dispose() method.
Here are the links:
MemoryCache Empty : Returns null after being set
http://forums.asp.net/t/1736572.aspx/1
My recommendation is to use the System.Web.Caching (HttpContext.Current.Cache)
UPDATE:
This issue has been fixed by MS. Check the accepted answer in the post below:
Runtime Cache Issue Resolved
|
I am adding caching to an ASP.NET web application. This is .NET 4, so I can use the classes in the System.Runtime.Caching namespace (which, as I understand it, was added to provide similar functionality to that found in System.Web.Caching, but for non-Web-apps.)
But since this is a web app, am I better off using System.Web.Caching? Or is the newer System.Runtime.Caching superior in some way?
|
Is System.Web.Caching or System.Runtime.Caching preferable for a .NET 4 web application
|
You can use a very simple solution that consist in append a hash to your scripts files. Each time your App is deployed you serve your files with a different hash automatically via a gulp/grunt task. As an example you can use gulp-rev. I use this technique in all my projects and works just fine, this automatized in your build/deploy process can be a solution for all your projects.
Yeoman generator for AngularJS generator-gulp-angular (this was my generator of choice) use this solution to ensure that the browser load the new optimazed file and not the old one in cache. Please create a demo project and play with it and you will see it in action.
|
This question already has answers here:
Clear browser cache in Angular
(4 answers)
Closed 3 years ago.
My angular application is constantly changing these days because our team runs rapid updates right now.
Because of cache our clients does not always have the newest version of our code.
So is there a way in angular to force the browser to clear cache?
|
AngularJs force browser to clear cache [duplicate]
|
Using meta HTML tags, Disable browser caching:-
<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0">
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
or,
Add headers in http request as:-
headers = new Headers({
'Cache-Control': 'no-cache, no-store, must-revalidate, post-
check=0, pre-check=0',
'Pragma': 'no-cache',
'Expires': '0'
});
|
I'm writing an Angular SPA app, that uses HttpClient to get values from my backend.
What is the easy way to tell it not to cache? The first time I ask it gets the value, then it refuses to make subsequent queries.
Thanks,
Gerry
|
How to disable caching with HttpClient get in Angular 6
|
Guava provides no way to refresh the cache in bulk, but you can schedule a periodic refresh yourself:
LoadingCache<K, V> cache = CacheBuilder.newBuilder()
.refreshAfterWrite(15, TimeUnit.MINUTES)
.maximumSize(100)
.build(new MyCacheLoader());
for (K key : cache.asMap().keySet()) {
cache.refresh(key);
}
But in that case you may want to override the CacheLoader.reload(K, V) method in MyCacheLoader so it performs asynchronously.
As for the second question, no, you cannot set a per-entry expiration in Guava.
|
I am using Google Guava library for caching.
For automatic cache refresh we can do as follows:
cache = CacheBuilder.newBuilder()
.refreshAfterWrite(15, TimeUnit.MINUTES)
.maximumSize(100)
.build(....);
However, automatic refreshes are performed when the first stale request for an entry occurs.
Is there a way to refresh it automatically even though no requests came for cache data? Like for every 15 minutes the cache data should be pulled from Db and load it, no matter whether anybody called cache data or not.
Also, Guava's cache expiry time is for entire cache. Is it possible to expire cache values based on key? Like cache data with key "NOT_SO_FREQ_CHANGE_DATA" to expire for every 1 hour and data with key "FREQ_CHANGING_DATA" should expire for every 15 minutes?
|
How to automatically refresh Cache using Google Guava?
|
It is actually sensible to associate Redis and MongoDB: they are good team players. You will find more information here:
MongoDB with redis
One critical point is the resiliency level you need. Both Redis and MongoDB can be configured to achieve an acceptable level of resiliency, and these considerations should be discussed at design time. Also, it may put constraint on the deployment options: if you want master/slave replication for both Redis and MongoDB you need at least 4 boxes (Redis and MongoDB should not be deployed on the same machine).
Now, it may be a bit simpler to keep Redis for queuing, pub/sub, etc ... and store the user data in MongoDB only. Rationale is you do not have to design similar data access paths (the difficult part of this job) for two stores featuring different paradigms. Also, MongoDB has built-in horizontal scalability (replica sets, auto-sharding, etc ...) while Redis has only do-it-yourself scalability.
Regarding the second question, writing to both stores would be the easiest way to do it. There is no built-in feature to replicate Redis activity to MongoDB. Designing a daemon listening to a Redis queue (where activity would be posted) and writing to MongoDB is not that hard though.
|
The Setup:
Imagine a 'twitter like' service where a user submits a post, which is then read by many (hundreds, thousands, or more) users.
My question is regarding the best way to architect the cache & database to optimize for quick access & many reads, but still keep the historical data so that users may (if they want) see older posts. The assumption here is that 90% of users would only be interested in the new stuff, and that the old stuff will get accessed occasionally. The other assumption here is that we want to optimize for the 90%, and its ok if the older 10% take a little longer to retrieve.
With this in mind, my research seems to strongly point in the direction of using a cache for the 90%, and then to also store the posts in another longer-term persistent system. So my idea thus far is to use Redis for the cache. The advantages is that Redis is very fast, and also it has built in pub/sub which would be perfect for publishing posts to many people. And then I was considering using MongoDB as a more permanent data store to store the same posts which will be accessed as they expire off of Redis.
Questions:
1. Does this architecture hold water? Is there a better way to do this?
2. Regarding the mechanism for storing posts in both the Redis & MongoDB, I was thinking about having the app do 2 writes: 1st - write to Redis, it then is immediately available for the subscribers. 2nd - after successfully storing to Redis, write to MongoDB immediately. Is this the best way to do it? Should I instead have Redis push the expired posts to MongoDB itself? I thought about this, but I couldn't find much information on pushing to MongoDB from Redis directly.
|
Architecture for Redis cache & Mongo for persistence
|
Answer taken from Kevin Low comment
If you can use private APIs (as in an AdHoc only app, for example) use this UIImage method to remove all images from cache
[UIImage _flushSharedImageCache];
|
It is well known that UIImage caches its image data when the image is loaded using the imageNamed: method.
From apple documentation:
https://developer.apple.com/documentation/uikit/uiimage/1624146-imagenamed
imageNamed:
Discussion: 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.
Because of that, after loading several images with imageNamed: I noticed a large increase of memory usage and also that the memory was kept in use even after the controller that loaded the images was dealloc. (at least it didn't increase again when I alloc the same controller)
That made me wonder if there is any way to clear the cache used by UIImage programmatically at any given time of my application lifecycle or even control some cache parameters (like the maximum memory that it can use, for example)
I know that I could easily solve this problem by using initWithData, imageWithData, imageWithContentsOfFile or any other initializer instead of imageNamed, but this cache behavior is desired when using several images, like inside a UITableView.
Any thoughts on how to accomplish that?
EDIT:
After some answers I just want to make it clear that there is a huge gap between needing to do something and having the possibility to do something. As I pointed out, I know that the OS takes care of that cache for me, I am just trying to see the limitations that the iOS SDK imposes.
|
Is there a way to clear the cache used by UIImage class?
|
The delay seems to be related to instantiating AVAudioPlayer for the first time. If I load any audio, run [audioPlayer prepareToPlay] and then immediately release it, the load times for all of my other audio is very close to imperceptible. So now I'm doing that in applicationDidFinishLaunching and everything else runs well.
I can't find anything about this in the docs, but it certainly seems to be the case.
|
I'm trying to eliminate startup lag when playing a (very short -- less than 2 seconds) audio file via AVAudioPlayer on the iPhone.
First, the code:
NSString *audioFile = [NSString stringWithFormat:@"%@/%@.caf", [[NSBundle mainBundle] resourcePath], @"audiofile"];
NSData *audioData = [NSData dataWithContentsOfMappedFile:audioFile];
NSError *err;
AVAudioPlayer *audioPlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithData:audioData error:&err];
audioPlayer.delegate = self;
[audioPlayer play];
I also implement the audioPlayerDidFinishPlaying method to release the AVAudioPlayer once I'm done.
The first time I play the audio the lag is palpable -- at least 2 seconds. However, after that the sound plays immediately. I suspect that the culprit, then, is the [NSData dataWithContentsOfMappedFile] taking a long time reading from the flash initially, but then being fast on later reads. I'm not sure how to test that, though.
Is that the case? If so, should I just pre-cache the NSData objects and be aggressive about clearing them in low memory conditions?
|
Slow start for AVAudioPlayer the first time a sound is played
|
I know that this thread has been answered, but I have tried a library that has worked great. I was using ASIHttpRequest before and the difference is big.
https://github.com/rs/SDWebImage
Also, if someone needs to Resize or Crop the remote images, and have the same features that SDWebImage provide, I have integrated SDWebImage library with UIImage+Resize library (by Trevor Harmon), and created an example project. I modified the code of SDWebImage to deal with transformations (crop, resize).
The project is public on https://github.com/toptierlabs/ImageCacheResize. Feel free to use it!
|
I want an image loading and caching library for iOS that
loads images asynchronously,
caches images, with a configurable cache size and LRU behaviour,
checks to see if images have been updated, using HTTP HEAD,
doesn't cache anything in the event of an error code or an invalid image.
I've looked at HJCache, but it only satisfies the first two of these criteria. Is there something better?
|
iOS - Caching and loading images asynchronously
|
There are different reasons for that.
L2 exists in the system to speedup the case where there is a L1 cache miss. If the size of L1 was the same or bigger than the size of L2, then L2 could not accomodate for more cache lines than L1, and would not be able to deal with L1 cache misses. From the design/cost perspective, L1 cache is bound to the processor and faster than L2. The whole idea of caches is that you speed up access to the slower hardware by adding intermediate hardware that is more performing (and expensive) than the slowest hardware and yet cheaper than the faster hardware you have. Even if you decided to double the L1 cache, you would also increment L2, to speedup L1-cache misses.
So why is there L2 cache at all? Well, L1 cache is usually more performant and expensive to build, and it is bound to a single core. This means that increasing the L1 size by a fixed quantity will have that cost multiplied by 4 in a dual core processor, or by 8 in a quad core. L2 is usually shared by different cores --depending on the architecture it can be shared across a couple or all cores in the processor, so the cost of increasing L2 would be smaller even if the price of L1 and L2 were the same --which it is not.
|
Why is the size of L1 cache smaller than that of the L2 cache in most of the processors ?
|
Why is the size of L1 cache smaller than that of the L2 cache in most of the processors?
|
If you are using Doctrine already just use those cache classes.
Add a service to config.yml:
services:
cache:
class: Doctrine\Common\Cache\ApcCache
And use it in your controller:
if ($fooString = $this->get('cache')->fetch('foo')) {
$foo = unserialize($fooString);
} else {
// do the work
$this->get('cache')->save('foo', serialize($foo));
}
|
I need to cache some application specific data using Symfony 2's caching system so that I can run cache:clear to clear it. All the cache relies under app/cache but how do I actually go about caching data?
http://symfony.com/doc/current/cookbook/index.html
The only topic I see is about HTML caching with Varnish.
|
How to cache in Symfony 2?
|
HttpRuntime.Cache only provides severals methods and I think I'm able
to implement these methods with Dictionary by myself.
You think wrong. HttpRuntime.Cache is much more than a simple dictionary. It offers thread-safety and cache expiration policies. It provides possibilities of using custom implementation and benefit from distributed caching which is helpful in web farms. Implementing this with dictionaries could be lots of work that you probably don't want to venture into as you will be basically reinventing the wheels and even if reinventing wheels doesn't bother you chances for getting it right are slim.
2)If HttpRuntime.Cache is much better than Dictionary, why some people
would like to implement their own cache framework.
People wouldn't want to do that.
3) How about MS Enterprise Cache Block?
That's heavy artillery which is not always necessary when you need simple caching which could be achieved with what the framework already provides you out of the box.
Remark: In .NET 4.0 you should use the new System.Runtime.Caching namespace instead of HttpRuntime.Cache.
So to answer your question: Should I use HttpRuntime.Cache
Yes, unless you are using .NET 4.0 in which case you should use classes from the new System.Runtime.Caching namespace.
|
I'm a beginner in asp.net, and have a few question of Cache:
HttpRuntime.Cache only provides severals methods and I think I'm able to implement these methods with Dictionary by myself.
If HttpRuntime.Cache is much better than Dictionary, why some people would like to implement their own cache framework.
How about MS Enterprise Cache Block?
|
Should I use HttpRuntime.Cache?
|
Unless ADB is running as root (as it would on an emulator) you cannot generally view anything under /data unless an application which owns it has made it world readable. Further, you cannot browse the directory structure - you can only list files once you get to a directory where you have access, by explicitly entering its path.
Broadly speaking you have five options:
Do the investigation within the owning app
Mark the files in question as public, and use something (adb shell or adb pull) where you can enter a full path name, instead of trying to browse the tree
Have the owning app copy the entire directory to the SD card
Use an emulator or rooted device where adb (and thus the ddms browser's access) can run as root (or use a root file explorer or a rooted device)
use adb and the run-as tool with a debuggable apk to get a command line shell running as the app's user id. For those familiar with the unix command line, this can be the most effective (though the toolbox sh on android is limited, and uses its tiny vocabulary of error messages in misleading ways)
|
Is there any way to dynamically view the application specific cache in Android? I'm saving images to the cache (/data/data/my_app_package/cache) and I'm 99% sure they're saving there, but not sure how long they're staying around.
When I look in the cache using the DDMS File Explorer within Eclipse, it's always empty. I've also tried examining the appropriate cache dir in ADB and again it's always empty.
Any suggestions?
|
How do I view Android application specific cache?
|
On my system, an Intel Xeon X5570 @ 2.93 GHz I was able to get perf stat to report cache references and misses by requesting those events explicitly like this
perf stat -B -e cache-references,cache-misses,cycles,instructions,branches,faults,migrations sleep 5
Performance counter stats for 'sleep 5':
10573 cache-references
1949 cache-misses # 18.434 % of all cache refs
1077328 cycles # 0.000 GHz
715248 instructions # 0.66 insns per cycle
151188 branches
154 faults
0 migrations
5.002776842 seconds time elapsed
The default set of events did not include cache events, matching your results, I don't know why
perf stat -B sleep 5
Performance counter stats for 'sleep 5':
0.344308 task-clock # 0.000 CPUs utilized
1 context-switches # 0.003 M/sec
0 CPU-migrations # 0.000 M/sec
154 page-faults # 0.447 M/sec
977183 cycles # 2.838 GHz
586878 stalled-cycles-frontend # 60.06% frontend cycles idle
430497 stalled-cycles-backend # 44.05% backend cycles idle
720815 instructions # 0.74 insns per cycle
# 0.81 stalled cycles per insn
152217 branches # 442.095 M/sec
7646 branch-misses # 5.02% of all branches
5.002763199 seconds time elapsed
|
According to perf tutorials, perf stat is supposed to report cache misses using hardware counters. However, on my system (up-to-date Arch Linux), it doesn't:
[joel@panda goog]$ perf stat ./hash
Performance counter stats for './hash':
869.447863 task-clock # 0.997 CPUs utilized
92 context-switches # 0.106 K/sec
4 cpu-migrations # 0.005 K/sec
1,041 page-faults # 0.001 M/sec
2,628,646,296 cycles # 3.023 GHz
819,269,992 stalled-cycles-frontend # 31.17% frontend cycles idle
132,355,435 stalled-cycles-backend # 5.04% backend cycles idle
4,515,152,198 instructions # 1.72 insns per cycle
# 0.18 stalled cycles per insn
1,060,739,808 branches # 1220.015 M/sec
2,653,157 branch-misses # 0.25% of all branches
0.871766141 seconds time elapsed
What am I missing? I already searched the man page and the web, but didn't find anything obvious.
Edit: my CPU is an Intel i5 2300K, if that matters.
|
Why doesn't perf report cache misses?
|
Static variables retain their assigned values over repeated calls to the function. They're basically like global values that are only "visible" to that function.
The initializer statement is only executed once however.
This code initializes dateFormatter to nil the first time the function is used. On every subsequent call to the function a check is made against value of dateFormatter. If it's not set (which will only be true the first time) a a new dateFormatter is created. If it is set then the static dateFormatter variable will be used instead.
It's worth becoming familiar with static variables. They can be very convenient but have downsides too (in this example it's impossible to release the dateFormatter object for example).
Just a tip: Sometimes it can be educational to place a breakpoint in the code and have a look to see what's going on. As the complexity of your programs increase this will become an invaluable skill.
|
I'm looking at the following apple example source code:
/*
Cache the formatter. Normally you would use one of the date formatter styles (such as NSDateFormatterShortStyle), but here we want a specific format that excludes seconds.
*/
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"h:mm a"];
}
Trying to figure out:
Why use the static keyword?
How this equates to a cached variable if you set it to nil each time the method is called.
The code is from Example 4 in the Tableview Suite demo
|
Using static keyword in objective-c when defining a cached variable
|
31
Redis is a (sort of) in-memory noSQL database; but I found that my copy (running on linux) dumps to /var/lib/redis/dump.rdb
Share
Improve this answer
Follow
answered Jun 6, 2015 at 15:50
Alexx RocheAlexx Roche
3,21711 gold badge3434 silver badges3939 bronze badges
Add a comment
|
|
I am using redis for pub/sub as well as for server side cache. I mean my app server has redis server running as one process (functioning as a cache as well) . I have several thin clients (running redis client) connected to this app server in pub/sub mode. I would like to know where redis stores the cache data ? in server alone or there will be a copy in the clients as well. Also is it a good idea to use Redis in this fashion if there are close to 100 redis clients connected to server through pub/sub channel.
Thanks
|
Where does Redis store the data
|
CacheBuilder.build() returns a non-loading cache. Just what you want. Just use
Cache<String, String> cache = CacheBuilder.newBuilder().build();
|
My java app has a cache, and I'd like to swap out the current cache implementation and replace it with the guava cache.
Unfortunately, my app's cache usage doesn't seem to match the way that guava's caches seem to work. All I want is to be able to create an empty cache, read an item from the cache using a "get" method, and store an item in the cache with a "put" method. I do NOT want the "get" call to be trying to add an item to the cache.
It seems that the LoadingCache class has the get and put methods that I need. But I'm having trouble figuring out how to create the cache without providing a "load" function.
My first attempt was this:
LoadingCache<String, String> CACHE = CacheBuilder.newBuilder().build();
But that causes this compiler error: incompatible types; no instance(s) of type variable(s) K1,V1 exist so that Cache conforms to LoadingCache
Apparently I have to pass in a CacheLoader that has a "load" method.
(I guess I could create a CacheLoader that has a "load" method that just throws an Exception, but that seems kind of weird and inefficient. Is that the right thing to do?)
|
using guava cache without a load function
|
Yes, output caching is not what you are looking for. You can cache the data in memory with MemoryCache for example, http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx . However, you will lose that data if the application pool gets recycled. Another option is to use a distributed cache like AppFabric Cache or MemCache to name a few.
|
I have the need to cache a collection of objects that is mostly static (might have changes 1x per day) that is avaliable in my ASP.NET Web API OData service. This result set is used across calls (meaning not client call specific) so it needs to be cached at the application level.
I did a bunch of searching on 'caching in Web API' but all of the results were about 'output caching'. That is not what I'm looking for here. I want to cache a 'People' collection to be reused on subsequent calls (might have a sliding expiration).
My question is, since this is still just ASP.NET, do I use traditional Application caching techniques for persisting this collection in memory, or is there something else I need to do? This collection is not directly returned to the user, but rather used as the source behind the scenes for OData queries via API calls. There is no reason for me to go out to the database on every call to get the exact same information on every call. Expiring it hourly should suffice.
Any one know how to properly cache the data in this scenario?
|
Caching Data in Web API
|
A build-time argument can be specified to forcibly break the cache from that step onwards. For example, in your Dockerfile, put
ARG CACHE_DATE=not_a_date
and then give this argument a fresh value on every new build. The best, of course, is the timestamp.
docker build --build-arg CACHE_DATE=$(date +%Y-%m-%d:%H:%M:%S) ...
Make sure the value is a string without any spaces, otherwise docker client will falsely take it as multiple arguments.
See a detailed discussion on Issue 22832.
|
In my Dockerfile I use curl or ADD to download the latest version of an archive like:
FROM debian:jessie
...
RUN apt-get install -y curl
...
RUN curl -sL http://example.com/latest/archive.tar.gz --output archive.tar.gz
...
ADD http://example.com/latest/archive2.tar.gz
...
The RUN statement that uses curl or ADD creates its own image layer. That will be used as a cache for future executions of docker build.
Question: How can I disable caching for that instructions?
It would be great to get something like cache invalidation working there. E.g. by using HTTP ETags or by querying the last modified header field. That would give the possibility to do a quick check based on the HTTP headers to decide whether a cached layer could be used or not.
I know that some dirty tricks could help e.g. executing a download shell script in the RUN statement instead. Its filename will be changed before the docker build is triggered by our build system. And I could do the HTTP checks inside that script. But then I need to store either the last used ETag or the last modified to a file somewhere. I am wondering whether there is some more clean and native Docker functionality that I could use, here.
|
How can I prevent a Dockerfile instruction from being cached?
|
Ok, so, in order to use caching for your queryset:
class ProductListAPIView(generics.ListAPIView):
def get_queryset(self):
return get_myobj()
serializer_class = ProductSerializer
You'd probably want to set a timeout on the cache set though (like 60 seconds):
cache.set(cache_key, result, 60)
If you want to cache the whole view:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class ProductListAPIView(generics.ListAPIView):
serializer_class = ProductSerializer
@method_decorator(cache_page(60))
def dispatch(self, *args, **kwargs):
return super(ProductListAPIView, self).dispatch(*args, **kwargs)
|
I'm using Memcached as backend to my django app. This code works fine in normal django query:
def get_myobj():
cache_key = 'mykey'
result = cache.get(cache_key, None)
if not result:
result = Product.objects.all().filter(draft=False)
cache.set(cache_key, result)
return result
But it doesn't work when used with django-rest-framework api calls:
class ProductListAPIView(generics.ListAPIView):
def get_queryset(self):
product_list = Product.objects.all()
return product_list
serializer_class = ProductSerializer
I'm about to try DRF-extensions which provide caching functionality:
https://github.com/chibisov/drf-extensions
but the build status on github is currently saying "build failing".
My app is very read-heavy on api calls. Is there a way to cache these calls?
Thank you.
|
How to cache Django Rest Framework API calls?
|
You could use the RemoveOutputCacheItem method.
Here's an example of how you could use it:
public class HomeController : Controller
{
[OutputCache(Duration = 60, Location = OutputCacheLocation.Server)]
public ActionResult Index()
{
return Content(DateTime.Now.ToLongTimeString());
}
public ActionResult InvalidateCacheForIndexAction()
{
string path = Url.Action("index");
Response.RemoveOutputCacheItem(path);
return Content("cache invalidated, you could now go back to the index action");
}
}
The Index action response is cached on the server for 1 minute. If you hit the InvalidateCacheForIndexAction action it will expire the cache for the Index action. Currently there's no way to invalidate the entire cache, you should do it per cached action (not controller) because the RemoveOutputCacheItem method expects the url of the server side script that it cached.
|
Using ASP.Net MVC 3 I have a Controller which output is being cached using attributes [OutputCache]
[OutputCache]
public controllerA(){}
I would like to know if it is possible to invalidate the Cache Data (SERVER CACHE) for a Specific Controller or generally all the Cache data by calling another controller
public controllerB(){} // Calling this invalidates the cache
|
How to invalidate cache data [OutputCache] from a Controller?
|
This is the one I use to fix the exact same thing when I ran the PageSpeed Addon:
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
This goes into your .htaccess file.
Read up on this page for more information about how to set cache for additional file types and/or change the cache length:
http://www.askapache.com/htaccess/apache-speed-cache-control.html
|
I have recently analysed my website with pagespeed addon on firebug. It suggested me to set expiration on CSS, JS and image files.
I am wondering, how do I do this?
|
How do I set expiration on CSS, JS and Images?
|
Allocate a BIG char array (make sure it is too big to fit in L1 or L2 cache). Fill it with random data.
Start walking over the array in steps of n bytes. Do something with the retrieved bytes, like summing them.
Benchmark and calculate how many bytes/second you can process with different values of n, starting from 1 and counting up to 1000 or so. Make sure that your benchmark prints out the calculated sum, so the compiler can't possibly optimize the benchmarked code away.
When n == your cache line size, each access will require reading a new line into the L1 cache. So the benchmark results should get slower quite sharply at that point.
If the array is big enough, by the time you reach the end, the data at the beginning of the array will already be out of cache again, which is what you want. So after you increment n and start again, the results will not be affected by having needed data already in the cache.
|
As a school assignment, I need to find a way to get the L1 data cache line size, without reading config files or using api calls. Supposed to use memory accesses read/write timings to analyze & get this info. So how might I do that?
In an incomplete try for another part of the assignment, to find the levels & size of cache, I have:
for (i = 0; i < steps; i++) {
arr[(i * 4) & lengthMod]++;
}
I was thinking maybe I just need vary line 2, (i * 4) part? So once I exceed the cache line size, I might need to replace it, which takes sometime? But is it so straightforward? The required block might already be in memory somewhere? Or perpahs I can still count on the fact that if I have a large enough steps, it will still work out quite accurately?
UPDATE
Heres an attempt on GitHub ... main part below
// repeatedly access/modify data, varying the STRIDE
for (int s = 4; s <= MAX_STRIDE/sizeof(int); s*=2) {
start = wall_clock_time();
for (unsigned int k = 0; k < REPS; k++) {
data[(k * s) & lengthMod]++;
}
end = wall_clock_time();
timeTaken = ((float)(end - start))/1000000000;
printf("%d, %1.2f \n", s * sizeof(int), timeTaken);
}
Problem is there dont seem to be much differences between the timing. FYI. since its for L1 cache. I have SIZE = 32 K (size of array)
|
How to find the size of the L1 cache line size with IO timing measurements?
|
If you want to cache an action, based on all the query parameters (or say on nearly all of them), you can do:
caches_action :my_action, :cache_path => Proc.new { |c| c.params }
Or, maybe you want all but some params that you just use for Analytics (but that have no bearing on the records you're fetching):
caches_action :my_action, :cache_path => Proc.new { |c| c.params.delete_if { |k,v| k.starts_with?('utm_') } }
|
How can I cache my REST controller with Rails where my actions have query string parameters?
Example: GET /products/all.xml?max_price=200
Thx!
|
Rails action caching with querystring parameters
|
There is nothing in the base class libraries that does this.
On the free side, maybe something like C5's HashedLinkedList would work.
If you're willing to pay, maybe check out this C# toolkit. It contains an implementation.
|
I would like to implement a simple in-memory LRU cache system and I was thinking about a solution based on an IDictionary implementation which could handle an hashed LRU mechanism.
Coming from java, I have experiences with LinkedHashMap, which works fine for what I need: I can't find anywhere a similar solution for .NET.
Has anyone developed it or has anyone had experiences like this?
|
Is it there any LRU implementation of IDictionary?
|
I had the exactly same problem and spent a couple of hours...
I guess you are using older version of nginx (lower than 1.7)?
In nginx 1.7 you can use this directive:
proxy_ssl_server_name on;
This will force nginx to use SNI
Also, you should set the SSL protocols:
proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
For earlier versions you may be able to use this patch (but I can't verify that that is working):
http://trac.nginx.org/nginx/ticket/229
2019 Update: You should avoid TLSv1 and TLSv1.1 and disable them if possible. I'll leave them in the answer as they are still valid for SNI.
|
NGINX acting as a caching proxy encounters problems when fetching content from CloudFront server over HTTPS:
This is the extract from the NGINX's error log:
2014/08/14 16:08:26 [error] 27534#0: *11560993 SSL_do_handshake() failed (SSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure) while SSL handshaking to upstream, client: 82.33.49.135, server: localhost, request: "GET /static/images/media-logos/best.png HTTP/1.1", upstream: "https://x.x.x.x:443/static/images/media-logos/best.png",
I tried different proxy setting like proxy_ssl_protocols and proxy_ssl_ciphers but no combination worked.
Any ideas?
|
NGINX caching proxy fails with SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
|
We have a pretty comprehensive caching solution, as an example in conjunction with embedded hooks, in 0.6. It's a recipe to subclass Query, make it aware of Beaker, and allow control of query caching for explicit queries as well as lazy loaders via query options.
I'm running it in production now. The example itself is in the dist and the intro documentation is at http://www.sqlalchemy.org/docs/orm/examples.html#beaker-caching .
UPDATE: Beaker has now been replaced with dogpile caching: http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching
|
Does SQLAlchemy support some kind of caching so if I repeatedly run the same query it returns the response from cache instead of querying the database? Is this cache automatically cleared when the DB is updated?
Or what's the best way to implement this on a CherryPy + SQLAlchemy setup?
|
Does SQLAlchemy support caching?
|
Verify that the CloudFront distribution's Minimum TTL is set to 0. If it's set to any other value, CloudFront won't respect the no-cache header and will still cache the file for the Minimum TTL. More details about the caching directives can be found here:
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
If this doesn't help, try to debug the actual HTTP request for index.html and post the response headers here so we can have a look at them.
Also, instead of using no-cache for the index.html file, you can try using
public, must-revalidate, proxy-revalidate, max-age=0
This will allow CloudFront to store the file on the edge location, but it will force it to revalidate it with the origin with each request. If the file hasn't changed, CloudFront will not need to transfer the file's entire content from the origin. This can speed up the response time, especially for larger files.
|
I'm hosting a static website in S3 and using Cloudfront to cache files. I've essentially got 3 files with the following headers:
index.html (Cache-Control: no-cache)
app.js (Cache-Control: max-age=63072000, public)
style.css (Cache-Control: max-age=63072000, public)
My html file uses query string parameters that get updated every time I update my css or js files. I've configured s3 to pass these parameters through and I've verified that it works to invalidate cached resources. My index.html file looks something like this:
<html>
<head>
...
<link rel="stylesheet" href="app.css?v=14113e2c764">
</head>
<body>
...
<script src="app.js?v=14113e2c764"></script>
</body>
</html>
It seems to work great as I push updates all day, but when I come in the next morning and push my next change, The index.html file is out of date. Instead of having the correct ?v= parameter, it has the old one! The only way to fix it is to invalidate the html file manually. Then everything works for the rest of the day. The next day I have the same problem again.
What's going on here?
|
Amazon Cloudfront Cache-Control: no-cache header has no effect after 24 hours
|
If you're using ASP.NET, you could use the Cache class (System.Web.Caching).
Here is a good helper class: c-cache-helper-class
If you mean caching in a windows form app, it depends on what you're trying to do, and where you're trying to cache the data.
We've implemented a cache behind a Webservice for certain methods
(using the System.Web.Caching object.).
However, you might also want to look at the Caching Application Block. (See here) that is part of the Enterprise Library for .NET Framework 2.0.
|
I wanted to ask you what is the best approach to implement a cache in C#? Is there a possibility by using given .NET classes or something like that? Perhaps something like a dictionary that will remove some entries, if it gets too large, but where whose entries won't be removed by the garbage collector?
|
Caching in C#/.Net
|
You can append a variable to the end of each of your resources that changes with each deploy. For example you can name your stylesheets:
styles.css?id=1
with the id changing each time.
This will force the browser to download the new version as it cannot find it in its cache.
|
After deploying a new version of a website the browser loads everything from its cache from the old webpage until a force refresh is done. Images are old, cookies are old, and some AJAX parts are not working.
How should I proceed to serve the users with the latest version of the page after deploy?
The webpage is an ASP.Net webpage using IIS7+.
|
Website needs force refresh after deploy
|
You can use LinkedHashMap like this
You can remove by LRU or FIFO.
public static <K, V> Map<K, V> createLRUMap(final int maxEntries) {
return new LinkedHashMap<K, V>(maxEntries*10/7, 0.7f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries;
}
};
}
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I want an implementation of Map that has a maximum size. I want to use this as a cache and so oldest entries are removed once limit has been reached.
I also don't want to introduce a dependency on any 3rd party libraries.
|
How to limit the maximum size of a Map by removing oldest entries when limit reached [closed]
|
The main difference is because Caffeine uses ring buffers to record & replay events, whereas Guava uses ConcurrentLinkedQueue. The intent was always to migrate Guava over and it made sense to start simpler, but unfortunately there was never interest in accepting those changes. The ring buffer approach avoids allocation, is bounded (lossy), and cheaper to operate against.
The remaining costs are due to a design mismatch. The original author of MapMaker was enthusiastic about soft references as the solution to caching problems by deferring it to the GC. Unfortunately while that can seem fast in microbenchmarks, it has horrible performance in practice due to causing stop-the-world GC thrashing. The size-based solution had to be adapted into this work and that is not ideal. Caffeine optimizes for size-based and also gains an improved hash table, whereas Guava handles reference caching more elegantly.
Caffeine doesn't create its own threads for maintenance or expiration. It does defer the cost to the commonPool, which slightly improves user-facing latencies but not throughput. A future version might leverage CompletableFuture.delayedExecutor to schedule the next expiration event without directly creating threads (for users who have business logic depending on prompt removal notifications).
ConcurrentLinkedHashMap and MapMaker were written at the same time and CLHM has similar performance to Caffeine. I believe the difference is due to what scenarios the designers favored and optimized for, which impacted how other features would be implemented. There is low hanging fruit to allow Guava to have similar performance profile, but there isn't an internal champion to drive that (and even less so with Caffeine as a favored alternative).
|
According to these micro benchmarks it turns out that Caffeine is a way faster than Guava cache in both read and write operations.
What is the secret of Caffeine implementation? How it differs from the Guava Cache?
Am I right that in case of timed expiration Caffeine use a scheduled executor to perform appropriate maintenance operations in background?
|
Caffeine versus Guava cache
|
The static middleware does no server-side caching. It lets you do two methods of client-side caching: ETag and Max-Age:
If the browser sees the ETag with the page, it will cache it. The next time the browser loads the page it checks for the ETag number changes. If the file is exactly the same, and so is its ETag - the server responds with an HTTP 304("not modified") status code instead of sending all the bytes again and saves a bunch of bandwidth.
Etag is turned-on by default but you can turn it off like this:
app.use(express.static(myStaticPath, {
etag: false
}))
Max-age is will set the max-age to some amount of time so the browser will only request that resource after one day has passed.
app.use(express.static(myStaticPath, {
maxAge: '5000' // uses milliseconds per docs
}))
For more details you can read this article
By default it's on the hard-drive, but someone can use something like this
|
In ExpressJS for NodeJS, we can do the following:
app.use(express.static(__dirname + '/public'));
to serve all the static CSS, JS, and image files. My questions are these:
1) When we do that, does Express automatically cache the files in the server's memory or does it read from the hard disk every time one of the resources is served?
2) When we do that, does Express, using ETag by default, save the resources on the client's hard disk, or on the client's memory only?
|
Does express.static() cache files in the memory?
|
52
To clear the cache in Next.js app, follow these steps:
Stop the development server or any running Next.js processes.
Locate the root directory of your Next.js project.
Delete the .next directory. You can do this using the command line or file explorer.
Info: Once the .next directory is deleted, you can start the Next.js development server or rebuild your project, and Next.js will regenerate the necessary cache and build artifacts.
Keep in mind that deleting the .next directory will remove all the cached data and build artifacts, which means Next.js will need to rebuild the project and regenerate the cache on the next build or server start.
Share
Improve this answer
Follow
edited May 16, 2023 at 7:27
answered May 15, 2023 at 10:38
Sebastian Voráč MSc.Sebastian Voráč MSc.
3,96111 gold badge2323 silver badges2727 bronze badges
6
2
This is extremely helpful thank you
– AndrewLeonardi
Jul 7, 2023 at 18:59
1
@AndrewLeonardi Glad it is! Cheers
– Sebastian Voráč MSc.
Jul 11, 2023 at 16:01
2
You saved my life bro!!!
– Hoang Lam
Jul 28, 2023 at 17:27
1
Is there a better way in 2024 of doing this?
– jimmy
Jan 18 at 20:36
@jimmy what do you find unpleasant on deleting .next directory? There is not.
– Sebastian Voráč MSc.
Jan 20 at 11:12
|
Show 1 more comment
|
I have a product page at /products/[slug].js
and I use Incremental Static Generation for a wordpress/graphql site:
export async function getStaticProps(context) {
const {params: { slug }} = context
const {data} = await client.query(({
query: PRODUCT_SLUG,
variables: { slug }
}));
return {
props: {
categoryName: data?.productCategory?.name ?? '',
products: data?.productCategory?.products?.nodes ?? []
},
revalidate: 1
}
}
export async function getStaticPaths () {
const { data } = await client.query({
query: PRODUCT_SLUGS,
})
const pathsData = []
data?.productCategories?.nodes && data?.productCategories?.nodes.map((productCategory) => {
if (!isEmpty(productCategory?.slug)) {
pathsData.push({ params: { slug: productCategory?.slug } })
}
})
return {
paths: pathsData,
fallback: true,
}
}
Everything works as expected except one thing. If I delete a product from wordpress which was previously published, NextJs serves the cached page instead of showing 404 - Not found page, and I think this is how it is supposed to work, meaning that if something isn't rebuilt, show the previous (stale) page.
But how can I completely remove the cache for a specific product which has been deleted and it is not fetched again from the PRODUCT_SLUGS query ?
I have read the fallback options: true, false, blocking but none of them seems to work.
Is there a solution to this, either a next.config.js configuration or another work around ?
|
How to clear/delete cache in NextJs?
|
From HTTP Header Field Definitions:
14.9.3 Modifications of the Basic Expiration Mechanism
...
s-maxage
If a response includes an s-maxage directive, then for a shared cache (but not for a private cache), the maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header.
...
Note, "overrides". So, it would only make sense if you intend to specify a different maximum age for shared caches as compared to max-age, which would be used by end users.
In your particular example, they're the same, so specifying s-maxage is just unnecessary.
|
Considering that max-age applies to all the caches, and s-maxage only applies to shared caches (proxy and gateway cache)....
Does it make sense to use both directives in a non-expirable and public page?
Controller pseudo-code:
w = Response();
w.setPublic();
w.setMaxAge("1 year");
w.setShareMaxAge("1 year");
return w;
|
Does it make sense to have max-age and s-maxage in the Cache-Control HTTP header?
|
500k daily it's just 5-7 queries per second. If each request will be served for 0.2 sec, then you will have almost 0 simultaneous queries, so there is nothing to worry about.
Even if you will have 5 times more users - all should work fine.
You can just use INSERT DELAYED and tune your mysql.
About tuning: http://www.day32.com/MySQL/ - there is very useful script (will change nothing, just show you the tips how to optimize settings).
You can use memcache or APC to write log there first, but with using INSERT DELAYED MySQL will do almost same work, and will do it better :)
Do not use files for this. DB will serve locks much better, than PHP. It's not so trivial to write effective mutexes, so let DB (or memcache, APC) do this work.
|
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.
My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?
|
Best practice to record large amount of hits into MySQL database
|
I realize this question is old, but in the interest of helping anyone who finds this via search, its worth noting that .net v4 includes a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace:
https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx
The static reference to the default cache instance is: MemoryCache.Default
|
Scott Hanselman says yes.
Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.
MSDN says no.
The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.
So what should I think?
|
Is it OK to use HttpRuntime.Cache outside ASP.NET applications?
|
Flushing the shared pool should do it, but Tom Kyte lists a couple reasons below why you may not get the result you are expecting in some cases:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:6349391411093
|
I'm tuning SQL queries on an Oracle database. I want to ensure that all cached items are cleared before running each query in order to prevent misleading performance results. I clear out the shared pool (to get rid of cached SQL/explain plans) and buffer cache (to get rid of cached data) by running the following commands:
alter system flush buffer_cache;
alter system flush shared_pool;
Is there more I should be doing, or is this sufficient?
Thanks!
|
How to clear all cached items in Oracle
|
43
Rails has a built in rake task:
rake tmp:clear
Share
Improve this answer
Follow
answered May 28, 2013 at 18:29
gabeodessgabeodess
2,0762121 silver badges1616 bronze badges
0
Add a comment
|
|
I applied cache to my heroku rails app and it works well.
But everytime I deploy to heroku, I also want to clear cache automatically.
so I googled and I found this.
task :after_deploy, :env, :branch do |t, args|
puts "Deployment Complete"
puts "Cleaning all cache...."
FileUtils.cd Rails.root do
sh %{heroku run console}
sh %{Rails.cache.clear}
end
end
but when I raked this script, it just show the heroku console command line but the Rails.cache.clear command does not typed. (I guess that is because heroku console is interactive)
and
system "heroku console Rails.cache.clear"
doesn't work for cedar apps.
How can I solve this problem?
Thanks.
|
How can I clear rails cache after deploy to heroku?
|
31
//Use bellow code, it work for me.Set skip Memory Cache to true. it will load the image every time.
Glide.with(Activity.this)
.load(theImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(myImageViewPhoto);
Share
Improve this answer
Follow
answered Feb 22, 2017 at 10:01
Jaspreet KaurJaspreet Kaur
1,71011 gold badge1212 silver badges1818 bronze badges
7
1
Thanks for your reply ,but this does not full fill my requirnment
– Usman Saeed
Feb 23, 2017 at 6:46
You need to change url from server everytime, if you want to load image everytime. another wise Glide load same image which is first one, if URL not get changed.
– Jaspreet Kaur
Feb 23, 2017 at 7:05
1
Problem is url can not be changed
– Usman Saeed
Feb 23, 2017 at 7:15
1
The problem is that your photo will be loaded every time and this can consume time, in some cases where the image is too large, it can even lead to timeout. Maybe it is a good idea to save a boolean in sharedPreferences to say when the uri should be reloaded.
– Soon Santos
Nov 1, 2018 at 13:03
2
Turning the cache off is a really bad solution.
– Kocus
Nov 10, 2020 at 8:46
|
Show 2 more comments
|
I have the same url for an image. When I update this image more than one time it shows the previous image. The image and picture version on the server is updated but Glide is not showing the new image.I want to get new image every time and cache it .
Glide.with(context)
.load(Constants.COPY_LINK_BASE_URL + info.getDisplayPicture())
.placeholder(R.drawable.ic_profile).dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.signature(new (SettingManager.getUserPictureVersion(context)))
.into(ivUserProfilePhoto);
I can reproduce this bug by changing internet ,on one internet its change image as expected on other internet it remain same after 2 or 3 tries to changing image
|
Glide not updating image android of same url?
|
Some RewriteRule should handle that quite well.
In a Drupal configuration file I found:
# AddEncoding allows you to have certain browsers uncompress information on the fly.
AddEncoding gzip .gz
#Serve gzip compressed CSS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
# Serve gzip compressed JS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
# Serve correct content types, and prevent mod_deflate double gzip.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
This will make the job. You can put that either in a <Directory foo/> section or in a .htaccess file if you do not have access to apache configuration or if you want to slowdown your webserver.
|
I have simple question. I have webdirectory /css and inside is file style.css. I have manually gzipped this file and saved it as style.css.gz. I want to save CPU cycles to not have CSS file compressed at each request. How do I configure Apache to look for this .gz file and serve it instead of compressing .css file over and over again ?
Note: I don't want Apache to create .gz file itself. In my scenario I have to create .css.gz file manually - using PHP on specific requests.
|
How to force Apache to use manually pre-compressed gz file of CSS and JS files?
|
I'm assuming you're using the Twig engine, (the default templating engine for Symfony2). To disable caching in twig, so that you do not have to keep clearing the cache like so:
rm -rf app/cache/*
Navigate to your app config file (by defualt will be located in ../app/config/config.yml from your root directory). Scroll to the twig configuration settings (under twig:) and change the cache value (which should be pointing to the cache directory) to false like so:
twig:
cache: false
If you do not see any cache configuration entry, simply add the line above.
It may also be helpful to checkout the configuring reference for the Twig bundle: http://symfony.com/doc/2.0/reference/configuration/twig.html
After editing your config_dev.yml file, go to your terminal and run:
app/console cache:clear
|
Is there a way to disable the caching function in Symfony2? I tried to find the setting in the config* and parameters.ini files and I searched a lot. Ok, I found a few solutions, but nothing for the latest version (Symfony2).
WHY? Because I want to test new templates and functions without clearing the app/cache* all the time.
|
Symfony2 disable cache?
|
Cache coherence. When you scan horizontally, your data will be closer together in memory, so you will have less cache misses and thus performance will be faster. For a small enough rectangle, this won't matter.
|
I just stumbled upon this blog post about cache algorithms.
The author shows two code samples that loop through a rectangle and compute something (my guess is the computing code is just a placeholder).
On one of the examples, he scans the rectangle vertically, and on the other horizontally. He then says the second is fastest, and that every programmer should know why. Now I must not be a programmer, because to me it looks exactly the same.
Can anyone explain why the former is faster?
|
Fastest way to loop through a 2d array?
|
The NoStore property is used to inform proxy servers and browser that they should not store a permanent copy of the cached content by setting Cache-Control: no-store within the request header.
Duration simply specifies how long the content of the controller action should be cached, e.g. 10seconds. This will set the Cache-Control: max-age to >= 0. And also sets the Expires header to a valid timestamp.
To your initial question, no, the three variations do not have the same meaning.
[OutputCache(Duration = 0, Location = OutputCacheLocation.Client, VaryByParam = "*")]
create a cache-header like this
Cache-Control: private, max-age=0
Expires: Fri, 03 Jan 2014 12:32:15 GMT
[OutputCache(NoStore = true, Duration = 0, Location="None", VaryByParam = "*")]
creates the following cache-header:
Cache-Control: no-cache, no-store
Pragma: no-cache
Expires: -1
This is basically what you want to see if you want to prevent caching by all means. VaryByParam is optional (at least in MVC5) and the default is "*" anyways, so you can simply use [OutputCache(NoStore = true, Location = OutputCacheLocation.None)] instead.
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
even creates a public cache control...
Cache-Control: no-store0
There is a good post on SO which discusses the difference between max-age=0 and no-cache etc..
At the end all three might prevent caching your data but still have different meanings.
|
I am working on an asp.net MVC web application and I need to know if there are any differences when defining the OutputCache for my action methods as follow:-
[OutputCache(Duration = 0, Location = OutputCacheLocation.Client, VaryByParam = "*")]
VS
[OutputCache(NoStore = true, Duration = 0, Location="None", VaryByParam = "*")]
VS
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
Will all the above three setting prevent caching the data , or each on have different meaning ?
Second question what is the main difference between defining duration=0 & NoStore=true ? will both of them prevent caching ?
Thanks
|
OutputCache setting inside my asp.net mvc web application. Multiple syntax to prevent caching
|
.NET provides a few Cache classes
System.Web.Caching.Cache - default caching mechanizm in ASP.NET. You can get instance of this class via property Controller.HttpContext.Cache also you can get it via singleton HttpContext.Current.Cache. This class is not expected to be created explicitly because under the hood it uses another caching engine that is assigned internally.
To make your code work the simplest way is to do the following:
public class AccountController : System.Web.Mvc.Controller{
public System.Web.Mvc.ActionResult Index(){
List<object> list = new List<Object>();
HttpContext.Cache["ObjectList"] = list; // add
list = (List<object>)HttpContext.Cache["ObjectList"]; // retrieve
HttpContext.Cache.Remove("ObjectList"); // remove
return new System.Web.Mvc.EmptyResult();
}
}
System.Runtime.Caching.MemoryCache - this class can be constructed in user code. It has the different interface and more features like update\remove callbacks, regions, monitors etc. To use it you need to import library System.Runtime.Caching. It can be also used in ASP.net application, but you will have to manage its lifetime by yourself.
var cache = new System.Runtime.Caching.MemoryCache("MyTestCache");
cache["ObjectList"] = list; // add
list = (List<object>)cache["ObjectList"]; // retrieve
cache.Remove("ObjectList"); // remove
|
I'm looking for a real simple example of how to add an object to cache, get it back out again, and remove it.
The second answer here is the kind of example I'd love to see...
List<object> list = new List<Object>();
Cache["ObjectList"] = list; // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList"); // remove
But when I try this, on the first line I get:
'Cache' is a type, which is not valid in the given context.
And on the third line I get:
An object method is required for the non-static field blah blah blah
So, let's say I have a List<T>...
var myList = GetListFromDB()
And now I just wanna add myList to the cache, get it back out, and remove it.
|
Looking for a very simple Cache example
|
It's not a perfect solution, but we ended up creating a cleanup job at the end of our .gitlab-ci.yaml file that deletes the cache directory from the filesystem.
This way, each pipeline gets its own unique cache, without cluttering up the file system over time.
cleanup_job:
stage: cleanup
script:
- echo "Cleaning up"
- rm -rf "%CACHE_PATH%/%CI_PIPELINE_ID%"
when: always
where
CACHE_PATH: "C:/gitlab-runner/cache/group/project/repo/"
|
Is it possible to invalidate or clear a pipeline cache with the Gitlab CI after a pipeline completes?
My .gitlab-ci.yml file has the following global cache definition
cache:
key: "%CI_PIPELINE_ID%"
paths:
- './msvc/Project1`/bin/Debug'
- './msvc/Project2`/bin/Debug'
- './msvc/Project3`/bin/Debug'
The cache-key value specifies that each pipeline should maintain it's own cache, which is working fine, but the cache file continues to exist after the pipeline completes. With hundreds of pipelines being run, the size starts to add up and manually deleting the cache folder on our machine isn't a great solution.
I tried adding a cleanup job at the end of the pipeline
cleanup:
stage: cleanup
script:
- rm -rf './msvc/Project1/bin'
- rm -rf './msvc/Project2/bin'
- rm -rf './msvc/Project3/bin'
when: always
Which deletes the local files, but won't delete them from the cache.
Am I missing something here?
Currently running Gitlab-EE 10.3.3
|
Clearing the pipeline cache with Gitlab CI
|
I think I found a workaround:
The new version of the site only appears when the index.html file changes.
(the first file to be loaded)
If you leave the index.html and only change some js in other files then the site doesn't load the new version.
|
I've run into a problem where I add a web app to my iPad home screen (iOS 5.0.1 iPad 2), and when I open it it appears to be caching something behind the scenes, independent of Safari.
I've cleared out everything from Safari that's available in Settings (Clear History and Clear Cookies & Data), and when I navigate to the web app with Safari I see the app in its current state. However if I open the home screen bookmark I get the app in a pre-changed state.
I've seen a lot of information about using a cache.manifest to cache resources for offline use, but I'm not sure if that's relevant to this since I would like the exact opposite: cache nothing.
I've gone to the level of not even testing external resources; if I change some arbitrary test string in the body element of my index.html, the home screen bookmark does not show the updated text.
|
How do you force an iPad home screen bookmarked web app to refresh?
|
25
The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.
The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.
If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.
Share
Improve this answer
Follow
answered Sep 8, 2008 at 20:58
Andrew WilkinsonAndrew Wilkinson
10.8k33 gold badges3535 silver badges3838 bronze badges
Add a comment
|
|
I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?
|
Django Sessions
|
String#hashCode:
private int hash;
...
public int hashCode() {
int h = hash;
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Since the contents of a String never change, the makers of the class chose to cache the hash after it had been calculated once. This way, time is not wasted recalculating the same value.
|
So I read about HashMap. At one point it was noted:
"Immutability also allows caching the hashcode of different keys which makes the overall retrieval process very fast and suggest that String and various wrapper classes (e.g., Integer) provided by Java Collection API are very good HashMap keys."
I don't quite understand... why?
|
Why are immutable objects in hashmaps so effective?
|
cacheControl for Storage : https://firebase.google.com/docs/reference/js/firebase.storage.SettableMetadata#cacheControl
You'll have better serving with Hosting, and deployment with the firebase CLI is extremely simple. I think by default the Cache-Control on images in Hosting is 2 hours, and you can increase it globally with the .json.
https://firebase.google.com/docs/hosting/full-config#headers
Hosting can scale your site and move it to different edge nodes closer to where the demand is. Storage is limited to buckets, but you can specify a bucket for Europe, one for China, on for North America, etc..
Storage is better for user file uploads and Hosting was for static content (although they are rolling out dynamic Hosting with cloud functions I think)
|
I have a PWA running on Firebase. My image files are hosted on the Firebase Storage. I've noticed my browser doesn't save cache for files loaded from the storage system. The browser requests the files for every page refresh. It causes unnecessary delay and traffic.
My JS script loads the files from the Firebase Storage's download link, example: https://firebasestorage.googleapis.com/v0/b/discipulado-7b14b.appspot.com/o/book3.png?alt=media&token=65b2cde7-c8a4-45da-a743-401759663c17.
Can I cache those requests?
UPDATE
According to these answer I shouldn't use Firebase Storage to host files from my site. Just to manage downloads and uploads from users. Is this correct?
|
Set cache to files in Firebase Storage
|
You can enable Hibernate statistics generation be setting hibernate.generate_statistics property to true. Then you can monitor cache hit/miss count via SessionFactory.getStatistics().
Also, when SQL logging is enabled you can analyze cache behaviour by presence or absense of particular SQL queries.
It depends on many factors. See 21.2. The Second Level Cache and 21.4. The Query Cache
It depends on cache provider and its configuration. For example, EhCache can be configured to overflow to disk.
SessionFactory.getStatistics().getSecondLevelCacheStatistics() provides this information.
|
I am new in the hibernate's cache area.
What is the easiest way to check that the cache really works?
Does hibernate gnerate the same sql statements when cache is on?
Should it be any folder/file in filesystem with stored data (second-level cache)?
How to check how much cache is currently used?
Regards,
Marcin
|
Where and how to check that hibernate cache really works
|
You can think Redis as a shared data structure, while Ehcache is a memory block storing serialized data objects. This is the main difference.
Redis as a shared data structure means you can put some predefined data structure (such as String, List, Set etc) in one language and retrieve it in another language. This is useful if your project is multilingual, for example: Java the backend side , and PHP the front side. You can use Redis for a shared cache. But it can only store predefined data structure, you cannot insert any Java objects you want.
If your project is only Java, i.e. not multilingual, Ehcache is a convenient solution.
|
Which is better suited for the following environment:
Persistence not a compulsion.
Multiple servers (with Ehcache some cache sync must be required).
Infrequent writes and frequent reads.
Relatively small database (very less memory requirement).
I will pour out what's in my head currently. I may be wrong about these.
I know Redis requires a separate server (?) and Ehcache provides local cache so it must be faster but will replicate cache across servers (?). Updating all caches after some update on one is possible with Ehcache.
My question is which will suit better for the environment I mentioned?
Whose performance will be better or what are scenarios when one may outperform another?
Thanks in advance.
|
Redis or Ehcache?
|
The values you have there are OK, but meta http-equiv is highly unreliable. You should be using real HTTP headers (the specifics of how you do this will depend on your server, e.g. for Apache).
|
This question already has answers here:
How do we control web page caching, across all browsers?
(30 answers)
Closed 7 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
I have a HTML page. The problem is that I do not want to have the users to refresh the page each time I put on new content.
I have the following code in order to make sure that the page is not cached:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
The problem is, I still need to do a refresh on the page in order to get the most current content to show up. Am I doing something wrong? Should I be using some other tags?
|
Prevent caching of HTML page [duplicate]
|
primes, in your code, is not a function, but a constant, in haskellspeak known as a CAF. If it took a parameter (say, ()), you would get two different versions of the same list back if calling it twice, but as it is a CAF, you get the exact same list back both times;
As a ghci top-level definition, primes never becomes unreachable, thus the head of the list it points to (and thus its tail/the rest of the computation) is never garbage collected. Adding a parameter prevents retaining that reference, the list would then be garbage collected as (!!) iterates down it to find the right element, and your second call to (!!) would force repetition of the whole computation instead of just traversing the already-computed list.
Note that in compiled programs, there is no top-level scope like in ghci and things get garbage collected when the last reference to them is gone, quite likely before the whole program exits, CAF or not, meaning that your first call would take long, the second one not, and after that, "the future of your program" not referencing the CAF anymore, the memory the CAF takes up is recycled.
The primes package provides a function that takes an argument for (primarily, I'd claim) this very reason, as carrying around half a terabyte of prime numbers might not be what one wants to do.
If you want to really get down to the bottom of this, I recommend reading the STG paper. It doesn't include newer developments in GHC, but does a great job of explaining how Haskell maps onto assembly, and thus how thunks get eaten by strictness, in general.
|
I noticed that sometimes Haskell pure functions are somehow cached: if I call the function twice with the same parameters, the second time the result is computed in no time.
Why does this happen? Is it a GHCI feature or what?
Can I rely on this (ie: can I deterministically know if a function value will be cached)?
Can I force or disable this feature for some function calls?
As required by comments, here is an example I found on the web:
isPrime a = isPrimeHelper a primes
isPrimeHelper a (p:ps)
| p*p > a = True
| a `mod` p == 0 = False
| otherwise = isPrimeHelper a ps
primes = 2 : filter isPrime [3,5..]
I was expecting, before running it, to be quite slow, since it keeps accessing elements of primes without explicitly caching them (thus, unless these values are cached somewhere, they would need to be recomputed plenty times). But I was wrong.
If I set +s in GHCI (to print timing/memory stats after each evaluation) and evaluate the expression primes!!10000 twice, this is what I get:
*Main> :set +s
*Main> primes!!10000
104743
(2.10 secs, 169800904 bytes)
*Main> primes!!10000
104743
(0.00 secs, 0 bytes)
This means that at least primes !! 10000 (or better: the whole primes list, since also primes!!9999 will take no time) must be cached.
|
How to tell whether Haskell will cache a result or recompute it?
|
Spatial and temporal locality describe two different characteristics of how programs access data (or instructions). Wikipedia has a good article on locality of reference.
A sequence of references is said to have spatial locality if things that are referenced close in time are also close in space (nearby memory addresses, nearby sectors on a disk, etc.). A sequence is said to have temporal locality if accesses to the same thing are clustered in time.
If a program accesses every element in a large array and reads it once and then moves on to the next element and does not repeat an access to any given location until it has touched every other location then it is a clear case of spatial locality but not temporal locality. On the other hand, if a program spends time repeatedly accessing a random subset of the locations on the array before moving on to another random subset it is said to have temporal locality but not spatial locality. A well written program will have data structures that group together things that are accessed together, thus ensuring spatial locality. If you program is likely to access B soon after it accesses A then both A and B should be allocated near each other.
Your first example
A[0][1], A[0][2], A[0][3]
shows spatial locality, things that are accessed close in time are close in space. It does not show temporal locality because you have not accessed the same thing more than once.
Your second example
A[1], A[2], A[3]
also shows spatial locality, but not temporal locality.
Here's an example that shows temporal locality
A[1], A[2000], A[1], A[1], A[2000], A[30], A[30], A[2000], A[30], A[2000], A[30], A[4], A[4]
|
I am a little confused on the meanings of spatial and temporal locality. I'm hoping by looking at it with an array example it will help me understand it better.
In an example like this:
A[0][1], A[0][2], A[0][3].... etc
Does this demonstrate temporal locality? I see the same row is accessed many times but at different offsets... does this mean a different address is accessed?
Also, am I correct in saying that an example like this:
A[1], A[2], A[3]... etc
Demonstrates spatial locality?
Hopefully some clarification on how temporal and spatial locality work in real code will help me better understand them.
|
Temporal vs Spatial Locality with arrays
|
You're probably going to want four loops - two to iterate over the blocks, and then another two to perform the transpose-copy of a single block. Assuming for simplicity a block size that divides the size of the matrix, something like this I think, although I'd want to draw some pictures on the backs of envelopes to be sure:
for (int i = 0; i < n; i += blocksize) {
for (int j = 0; j < n; j += blocksize) {
// transpose the block beginning at [i,j]
for (int k = i; k < i + blocksize; ++k) {
for (int l = j; l < j + blocksize; ++l) {
dst[k + l*n] = src[l + k*n];
}
}
}
}
An important further insight is that there's actually a cache-oblivious algorithm for this (see http://en.wikipedia.org/wiki/Cache-oblivious_algorithm, which uses this exact problem as an example). The informal definition of "cache-oblivious" is that you don't need to experiment tweaking any parameters (in this case the blocksize) in order to hit good/optimal cache performance. The solution in this case is to transpose by recursively dividing the matrix in half, and transposing the halves into their correct position in the destination.
Whatever the cache size actually is, this recursion takes advantage of it. I expect there's a bit of extra management overhead compared with your strategy, which is to use performance experiments to, in effect, jump straight to the point in the recursion at which the cache really kicks in, and go no further. On the other hand, your performance experiments might give you an answer that works on your machine but not on your customers' machines.
|
So the obvious way to transpose a matrix is to use :
for( int i = 0; i < n; i++ )
for( int j = 0; j < n; j++ )
destination[j+i*n] = source[i+j*n];
but I want something that will take advantage of locality and cache blocking. I was looking it up and can't find code that would do this, but I'm told it should be a very simple modification to the original. Any ideas?
Edit: I have a 2000x2000 matrix, and I want to know how can I change the code using two for loops, basically splitting the matrix into blocks that I transpose individually, say 2x2 blocks, or 40x40 blocks, and see which block size is most efficient.
Edit2: The matrices are stored in column major order, that is to say for a matrix
a1 a2
a3 a4
is stored as a1 a3 a2 a4.
|
A Cache Efficient Matrix Transpose Program?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.