PHP 文件缓存数组的实现

好用的 PHP 文件缓存封装类 PHP 高速文件缓存类封装,支持自动过期失效,失效自动清空 立即下载
在一个试验性项目中,我需要从 sqlite3 数据库中随机读取一条记录给用户,要读取的数据表现在有23850条记录,按 skemu 分类,一般每个 skemu 下有 3000多条记录,原先我使用了 sqlite3 的随机查询语句:
 
  1. $query="SELECT * FROM shiti WHERE skemu = " . intval($kemuid) . " order by random() limit 1";  

然后在我现在用的电脑上没有感觉到明显迟延,但当我把服务器换到一个 P4 1.8G 512M内存的机器上运行时,感觉数据读取速度非常慢,需要2、3秒才能读出数据。如果每次用户要取一条随机记录,都执行这样一个随机查询的话,瓶颈将会出现在数据库查询过程中,难以想像这样的性能如何来适应众多用户的同时访问。为此,我考虑减少数据库的查询次数,先把记录 id 取出来放到数组中,然后从中再来随机取一条记录,同时存为文件供以后读取,这样以减少数据库查询的次数。
 
以下函数实现读出 id 集:
  1. static function getIDs($kemuid)  
  2. {  
  3.  $cachefile="cache/" . $kemuid . ".cache";  
  4.  $datas=array();  
  5.  if (!file_exists($cachefile)||time() < (filemtime($cachefile) + 14400))   
  6.  //缓存不存在或超过4小时  
  7.  {  
  8.   global $data;  
  9.   //读取 id 集  
  10.   $query="SELECT sid FROM shiti WHERE skemu = " . intval($kemuid);  
  11.   $res = $data->query($query);  
  12.   while($r = $data->fetchArray($res))  
  13.   {  
  14.    $datas[]=$r['sid'];  
  15.   }  
  16.   //写入缓存  
  17.   file_put_contents($cachefile,serialize($datas));     
  18.  }  
  19.  else  
  20.  {  
  21.   //读出缓存  
  22.   $fp = fopen($cachefile,'r');//读     
  23.   $datas = unserialize(fread($fp,filesize($cachefile)));//反序列化,并赋值    
  24.  }  
  25.  return $datas;  
  26. }  

调用它的读取随机记录函数:
  1. static function getRondam($kemuid)  
  2.  {  
  3.   global $data;  
  4.   $ids=self::getIDs($kemuid);  
  5.   $index=rand(0,count($ids)-1);  
  6.   $id=$ids[$index];  
  7.   $query="SELECT * FROM shiti WHERE sid = " . intval($id);  
  8.   $res = $data->query($query);  
  9.   $r = $data->fetchArray($res);  
  10.   $r['da']=$s;  
  11.   return $r;  
  12.  }  

这样比每次执行随机查询快多了,但是还是要比生成一个HTML缓存要慢一点,但那样需要把更多数据暴露给客户端,或是存储更多缓存,我想这已经是一个比较均衡的方案了。
 
这个解决办法的要点在于数组的序列化与反序列化,大家应该很容易看得懂。
QT应用编程: Win10系统下QT5.12搭建Android开发环境(配件齐全) 在win10系统下,搭建QT5.12.6 的Android开发环境。 阅读详情

相关推荐

微信小程序scroll-view,点击menu,滚动到锚点;滚动到锚点,激活menu。

首先看看效果图1、首先是点击菜单,滚动列表,这个实现比较简单。直接使用scroll-view 的 scroll-into-view属性,小程序文档。&lt;view class='container'&gt; &lt;!-- 菜单 --&gt; &lt;view class='menu'&gt; &lt;ul&gt; &lt;!-- scrollList 修改cate --&g...

weixin_39834214的博客 1万+

PHP 文件缓存的封装

项目搭建 index.php 为入口文件 Lib 目录为类库目录,Autoload.php 为自动加载类,用来实现类的自动加载。 Cache 目录里面创建 Cache.php 基类,通过一个简单的工厂函数进行调用。 Cache 目录里面创建 Interfaces 目录,通过接口的方式用来约束缓存的封装。File.php 里用来实现CacheInterface.php 定义的方法。 index...

业余敲代码 976

GNSS接收机性能测试指标详解:TTFF、位置精度、灵敏度等关键参数如何评估

本文详细解析了GNSS接收机性能测试的关键指标,包括首次定位时间(TTFF)、位置精度、灵敏度等,帮助工程师系统评估接收机性能。通过多频段协同定位和载波相位测试等技术,提升定位精度至亚米级。同时,介绍了灵敏度测试的极限挑战和授时精度的专业测试方案,为GNSS接收机的性能优化提供实用指导。

cuda7parallel的博客 963

php 生成缓存数组,PHP 资料缓存数组的实现

PHP 文件缓存数组的实现在一个试验性项目中,我需要从 sqlite3 数据库中随机读取一条记录给用户,要读取的数据表现在有23850条记录,按 skemu 分类,一般每个 skemu 下有 3000多条记录,原先我使用了 sqlite3 的随机查询语句:$query="SELECT * FROM shiti WHERE skemu = " . intval($kemuid) . " order ...

weixin_35782626的博客 190

Vue项目实战:海康WebControl插件从安装到预览功能全流程(附RSA加密避坑指南)

本文详细介绍了在Vue项目中集成海康威视WebControl插件的全流程,从环境准备、插件部署到核心功能实现。重点解析了使用JS_RequestInterface获取RSA公钥并进行加密参数初始化的关键步骤与常见避坑指南,帮助开发者高效完成监控视频预览功能的开发与调试。

linux6sysadmin的博客 1227

PHP数组缓存:三种方式JSON、序列化和var_export的比较

  使用PHP的站点系统,在面对大数据量的时候不得不引入缓存机制。有一种简单有效的办法是将PHP的对象缓存到文件里。下面我来对这3种缓存方法进行说明和比较。   第一种方法:JSON JSON缓存变量的方式主要是使用json_encode和json_decode两个php函数。json_encode可以将变量变成文本格式,这样就可以存到文件里。 使用样例如下: // Store c...

Just Code 449

Halcon-AOI外观缺陷检测系列

Halcon-AOI外观缺陷检测系列

Jumy_S的博客 1667

php 怎样数据缓存文件,PHP 实现文件缓存数组等数据

PHP 有Redis,Memcache等高速缓存,但是低端服务器可能就没有这些配置了,我们可以尝试着把经常用到的数据(如:数组、导航条、页面底部信息等)缓存到文件中,这样就能“快速的”获取相应的信息了。以下是尝试的一部分代码://自定义缓存classYCache{//从文件读取缓存//将json转换为普通格式//key要读取的键值publicstaticfunctionget...

weixin_30039395的博客 276

Pareto 优化 (Pareto Optimization) 算法详解及案例分析

Pareto 最优解是指在多目标优化问题中,无法通过改进一个目标而不损害其他目标的解。具体来说,对于一个解x∗x^*x∗,如果不存在另一个解xxx使得所有目标函数fixf_i(x)fi​x都不劣于fix∗f_i(x^*)fi​x∗,且至少有一个目标函数fjxf_j(x)fj​x优于fjx∗f_j(x^*)fj​x∗,则x∗x^*x∗是 Pareto 最优解。

闲人编程的博客 2761

FreeRTOS全攻略:从入门到精通

本文聚焦 FreeRTOS,从基础概念出发,阐述其开源、轻量级等优势。着重介绍 FreeRTOS 入门知识,涵盖内存管理、任务操作、同步互斥机制等核心内容。其中,空闲任务与钩子函数保障系统基础运行与功能扩展;队列、信号量、互斥锁和事件组等机制,分别从数据传递、资源访问控制、优先级问题解决及多任务同步等方面,为开发者提供高效的任务间协作与资源管理方案,助力开发者掌握 FreeRTOS 核心技术,为嵌入式项目开发筑牢基础。

邓邓子的博客 6358

php怎样数据缓存文件,几个简单的php数据文件缓存类

1.对于一般的变量,把该变量变成php语言的格式,写到文件中,用时只要include这个文件就相当于加载了cache了;2.对于array型的变量,把array转化为php语言定义array的字符串,写到文件中,用时也只要include就相当于加载了cache了;3.缓存cache时间上的控制,通过获取缓存文件的创建时间和现在的时间进行对比,如果没有到更新时间,直接读取缓存,如果到了更新时间,查询...

weixin_39726971的博客 185

构建基于知识图谱的金融监管合规系统

金融行业是一个高度监管的领域,金融机构需要遵守众多复杂的法规和政策。传统的金融监管合规方式往往依赖于人工审查和简单的规则引擎,效率低下且容易出错。构建基于知识图谱的金融监管合规系统的目的在于利用知识图谱强大的知识表示和推理能力,实现对金融业务数据的自动化分析和合规检查,提高监管合规的效率和准确性。本系统的范围涵盖了金融机构的各类业务,如银行业务、证券业务、保险业务等。

AI天才研究院 1167

php数据库缓存类,常见php数据文件缓存类汇总

本文实例汇总了常见php数据文件缓存类。分享给大家供大家参考。具体分析如下:数据文件缓存的做法我们常用的有php文件缓存与利用memcache来缓存数据,下面面我分别总结了memcache缓存数据与数据文件缓存。感兴趣的朋友可以参考一下。1.对于一般的变量,把该变量变成php语言的格式,写到文件中,用时只要include这个文件就相当于加载了cache了.2.对于array型的变量,把array转...

weixin_36223355的博客 245

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

php+数组存放文件名_php中将数组存到文件里的实现代码

php的数组十分强大,有些数据不存入数据库直接写到文件上,用的时候直接require第一次分享代码;(写得很烂..紧张纳紧张纳)php的数组十分强大,有些数据不存入数据库直接写到文件上,用的时候直接require。(实际中有用到把数组存在到文件中的功能,不过分享的代码跟实际应用中的有点不同)function cacheArr(&$data){if(!$data)throw new Exce...

weixin_39809793的博客 167

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

php如何把数组写入缓存文件中并取出后还原数组

在我们写程序的时候有过很多情况会用到数据缓存,比如特别大的数据,或者更新频率不需要让我别勤的数据,这时候我们可以先把数据存进缓存文件中,下次用到该数据时直接从缓存文件里面读取就可以了这样会加快代码执行速度 代码如下 //生成需要往缓存文件里面存储的数组 $array = array('123','csdn','中国加油'); //定义缓存数据存储的文件 $fileName = 'cache.tx...

weixin_44470902的博客 677

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

php 把数组保存为标准的数组格式,存储到文件中

<?php $file='./test.php'; $array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large')); cache_write($file,$array,'rows',false); //写入 functio...

weixin_30443895的博客 385

PHP保存输入文本,php将数组保存为文本格式的三种方法

$file='./cache/phone.php';$array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large'));cache_write($file,$array,'rows',false);//写入function cache_write($filename,$...

weixin_39932838的博客 303

php is_file 缓存,php 文件缓存函数

function createHashDir($sign){$md5 = md5($sign);if(!is_dir(MB_CACHE)) mkdir(MB_CACHE);for($i=1;$i<=4;$i++){$dir .= $md5{$i}.'/';if(!is_dir(MB_CACHE.$dir)){mkdir(MB_CACHE.$dir);}}return MB_CACHE.$di...

weixin_42393272的博客 199

php 把数组写到文件,php把数组写入文件

php把数组写入文件,通过序列和反序列实现。请看代码$file="./data/file.cache";file_put_contents($file,serialize($array));//写入缓存$file="./data/file.cache";$array = array("count" => "3000", "num" =>"300");//缓存file_put_co...

weixin_42517137的博客 213

php缓存数组到文件

php缓存数组到文件 static function getIDs($kemuid) { $cachefile="cache/" . $kemuid . ".cache"; $datas=array(); if (!file_exists($cachefile)||time() > (filemtime($cachefile) + 14400)) //...

weixin_30634661的博客 197

PHP如何将数组存入缓存TXT文件并取出后还原成数组

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33835690的博客 454

PHP 写入缓存

1.创建file.PHP <?php class File{ //封装方法 private $_dir; const EXT='.text';//文件后缀,定义为常量 public function __contruct(){ $this->_dir=dirname(__FILE__).'/files/';//默认存货缓存文件夹数据 } //$key...

ak47147258369的博客 459

php 生成缓存数组,如何把数组动态写进PHP文件作为文件缓存

?class="php" name="code">/*** @Purpose: 设置缓存文件信息* @Method Name:set_user_capacityCache()* @Parameter: int $uid 用户的uid, array $arr 存放的数据数组* @Return: 返回存放文件的字符长度*/function set_user_capacityCache($uid,...

weixin_28731231的博客 254

php代码cache_php cache类代码(php数据缓存类)

php的执行效率很高,速度很快,但是连接数据库、查询数据库等还是比较耗时的。如果访问量大的话会给数据库造成很大的负担,所以对于变化不经常的内容要做好php 数据cache(缓存)是十分必要的,我做了一个简单的php“文件缓存”的类,希望对大家有所帮助。思路是这样的:对于一般的变量,把该变量变成php语言的格式,写到文件中,用时只要include这个文件就相当于加载了cache了;对于array型的...

weixin_39520199的博客 164
上一篇: ajaxload.js--doCopy方法,网上常用的点击复制
下一篇: php redis
HackProgramer
博客等级 码龄12年 255粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值