How to set up cache in php

coldplay.xixi
Release: 2023-03-07 09:20:01
Original
4389 people have browsed it

设置php缓存的方法:1、使用Memcached高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载;2、使用Redis实现缓存;3、使用APC开放自由的PHP opcode缓存。

How to set up cache in php

设置php缓存的方法:

缓存技术可减轻服务器负载、降低网络拥塞、增强WWW可扩展性,其基本思想是利用客户访问的时间局部性,将客户访问过的内容在Cache中存放一个副本,当该内容下次被访问时,不必连接到驻留网站,而是由Cache中保留的副本提供。缓存是一个很重要的技术,下面是自己使用的几个缓存技术,记录一下。

1、文件缓存

2、Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信,php有memcached扩展,安装好了即可使用。

// 初始化
$cache = new Memcache();
$cache->pconnect(CACHE_HOSTNAME, CACHE_PORT);
// 写入
$cache->set(CACHE_PREFIX . $key, $value, MEMCACHE_COMPRESSED, $expire);(CACHE_PREFIX 为了避免命名冲突,最好加一个前缀,MEMCACHE_COMPRESSED一个标记,设置为0表示不压缩)
// 读取
$cache->get(CACHE_PREFIX . $key);
// 删除
$cache->delete(CACHE_PREFIX . $key);
Copy after login

3、Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。类似的安装好php扩展// 初始化$cache = new Redis();

// 初始化$cache = new \\Redis();
$cache->connect(CACHE_HOSTNAME, CACHE_PORT);
// 先检查是否存在,然后写入并设置有效时间
if($cache->exists($key)){  
    $cache->delete(CACHE_PREFIX . $key);
}
$cache->set(CACHE_PREFIX . $key, serialize($value));
$cache->expire(CACHE_PREFIX . $key, $expire);
// 读取
$cache->get(CACHE_PREFIX . $key);
Copy after login

4、APC

Alternative PHP Cache (APC) 是一个开放自由的PHP opcode 缓存。它的目标是提供一个自由、 开放,和健全的框架用于缓存和优化PHP的中间代码。

这个试了半天没成功,windows一开启就报错,记下以后再试。

php内置的,无需类似上面两种去连接初始化什么的。

// 写入
apc_store(CACHE_PREFIX . $key, $value, $expire);
// 读取
apc_fetch(CACHE_PREFIX . $key);
// 删除
apc_delete(CACHE_PREFIX . $key);
Copy after login

 相对第四个貌似是最简单的,但是好像配置不好配,网上找了半天没找到解决方案。

相关免费学习推荐:php编程(视频)

The above is the detailed content of How to set up cache in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!