Home > Article > Backend Development > PHP connections to NoSQL databases: MongoDB, Redis and more
Connect to NoSQL database in PHP: MongoDB: use MongoDB\Client class; Redis: use Redis class; Elasticsearch: use Elasticsearch\ClientBuilder class. Use Redis to cache WordPress pages: Create a Redis client; define a filter function to check whether the page exists in the cache; if it exists, output the cached page; otherwise, output the original page and cache it; enable cache filtering.
Connection of PHP to NoSQL database
NoSQL database (such as MongoDB, Elasticsearch, Redis) due to its flexibility, scalability and High-performance features are widely favored in modern application development. Here's how to connect to various NoSQL databases in PHP:
MongoDB
$client = new MongoDB\Client("mongodb://localhost:27017"); $db = $client->myDatabase; //选择数据库 $collection = $db->myCollection; //选择集合
Redis
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); //连接Redis服务器
Elasticsearch
$client = Elasticsearch\ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
Practical case: Using Redis to cache WordPress pages
The following is how to use Redis to cache WordPress pages:
//获取Redis客户端 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); //创建过滤缓存的函数 function cache_filter_func($buffer) { global $redis; $url = $_SERVER['REQUEST_URI']; //获取当前URL //检查Redis缓存中是否存在页面 $cached_page = $redis->get($url); //如果存在,则直接输出缓存页面 if ($cached_page) { echo $cached_page; } //否则,输出原始页面并缓存起来 else { $output = ob_get_contents(); //获取输出缓冲区内容 ob_end_clean(); //将页面写入Redis缓存 $redis->set($url, $output); //输出原始页面 echo $output; } } //启用缓存过滤 add_filter('wp_title_pri', 'my_cache_filter_func', 1);
The above is the detailed content of PHP connections to NoSQL databases: MongoDB, Redis and more. For more information, please follow other related articles on the PHP Chinese website!