帝国CMS redis随机调用信息。首先服务器确保安装redis扩展。写入信息ID到redis集合(帝国CMS后台自定义页面),下面小编开始讲解了哦,教程如下:
redis获取集合中信息ID
- <?php
- header("Content-Type:text/html;charset=utf-8");
- $redis=new Redis();
- try {
- $redis->connect('127.0.0.1', 6379);
- echo "Redis Server version: ". $redis->info()['redis_version'] ."<br />"; //显示版本
- $key='infoid';
- $deleted=$redis->del($key);
- $sql=$empire->query("select id from phome_ecms_news_index order by id");
- while($r=$empire->fetch($sql)){
- $redis->sADD($key,$r[id]);
- }
- }
- catch (Exception $e) {
- echo "Cannot connect to Redis server: " .$e->getMessage(). "<br />";
- }
- $redis->close();// 关闭连接
- ?>
调用帝国CMS随机信息(以下代码放到e/action/redis/下)
- <?php
- header("Content-Type:text/html;charset=utf-8");
- $redis=new Redis();
- try {
- $redis->connect('127.0.0.1', 6379);
- echo "Redis Server version: ". $redis->info()['redis_version'] ."<br />"; //显示版本
- $key='infoid';
- $members=$redis->sMembers($key);
- foreach ($members as $member) {
- echo $member . PHP_EOL;
- }
- }
- catch (Exception $e) {
- echo "Cannot connect to Redis server: " .$e->getMessage(). "<br />";
- }
- $redis->close();// 关闭连接
- ?>
- <?php
- require('../../class/connect.php'); //引入数据库配置文件和公共函数文件
- require('../../class/db_sql.php'); //引入数据库操作文件
- require('../../data/dbcache/class.php'); //引入栏目缓存文件
- $link=db_connect(); //连接MYSQL
- $empire=new mysqlquery(); //声明数据库操作类
- $editor=1; //声明目录层次
- $nu=(int)$_GET[num];
- if(!$nu){
- $nu=10;
- }
- $redis=new Redis();//连接
- $redis->connect('127.0.0.1', 6379);
- $key='infoid'; //写入内存的KEY键值
- $randomid=$redis->sRandMember($key,$nu); //获取集合取数据
- foreach($randomid as $data){
- $r=$empire->fetch1("select id,title,titleurl,writer,smalltext from {$dbtbpre}ecms_news where id='$data' order by id asc limit 1");
- ?>
- <li><a href="<?=$r[titleurl]?>" title="<?=$r[title]?>"><?=$r[title]?></a></li>
- <?
- }
- $redis->close();// 关闭连接
- db_close(); //关闭MYSQL链接
- $empire=null; //注消操作类变量
- ?>
直接访问PHP查看效果。在模板中调用可以参考以下代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Fetch Example</title>
- </head>
- <body>
- <div id="output"></div>
- <script>
- fetch('/e/action/redis/redis.php')
- .then(response => response.text())
- .then(data => {
- document.getElementById('output').innerHTML = data;
- })
- .catch(error => console.error('Error:', error));
- </script>
- </body>
- </html>