Using the same MySQL query with all users without having to reconnect to the database [closed]

StackOverflow https://stackoverflow.com/questions/13558098

Pergunta

I'll try to be simple, so what i need is, perform a MySQL query (selecting records from a table) let's say ill produce the query with cron jobs or whatever every 5 minutes, and save this query or results to a file or a global variable if it's possible, and then serving it to all clients (i.e. using the same query to all users, without having to reconnect to that database.) Now i know some of you will tell me to use cache, but i searched for it, and if the table changes there will be new cache, and my table is constantly changing, now i don't care if the table has changed, i just want to serve the same query to all clients. Is that possible? your recommendations please. Thanks.

The cache expires automatically when the table is modified (inserts, updates, delete's, etc). And my table is constantly changing, so is it possible to save a cache even if the table has been modified? or should i look for a different solution?

Foi útil?

Solução

If the result set isn't too big, you could cache it into a generated script like so:

file_put_contents(
    'mycache.php', 
    '<?php return ' . var_export($results, true) . ' ?>'
);

Then to use it:

$results = include 'mycache.php';

Outras dicas

If you are always using same way (function, class) to perform database read and write,
you can always putting a cache expireation after each action

for example:

function add() // update, delete
{
  if (added) $this->expire_cache();
}

function search()
{
  if (results) $this->set_cache(results);
}

function expire_cache()
{
  // do expire or purge cache
}

function set_cache( $db_results )
{
  // saving the database result OR computed result into cache
  // memcache, redis, disk cache or anything
}

However, the purpose of having cache is to serve the request without having to get expensive resource like database query,
but if you are required to update very frequently, then the cache implementation is not so useful

memcache example : http://php.net/manual/en/book.memcache.php

you would need to compile memcache module, setup & start a memcache server in order to use memcache

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top