当论坛帖子数量十分庞大时,直接使用MySQL limit查询进行分页会变得十分缓慢,因此我们需要使用其他技术辅助进行分页处理。
假如我们帖子列表和发帖都是用Ajax的POST来提交数据的,请用PHP,并且结合MySQL和redis的ZSET编写程序,实现以下基本逻辑:
1、处理获取帖子列表页内容的AJax请求,AJax请求的参数为page(页码),程序需要返回当前页码的所有帖子的数据,返回的数据类型是json格式的,请自行规定具体接口数据结构。
2、处理发表帖子的Ajax post请求,实现把数据写入到MYSQL等操作。
具体需求如下:
1、 分页是按发帖时间倒序排列,每页50条;
2、 不允许使用开源框架;
3、 进行必要的封装;
4、 假设Redis和MySQL服务器使用localhost,用户名及密码均为www.huchen.net;
5、 代码结构良好,PhpDoc注释清晰;
分析下需求 帖子的发帖时间倒序 就是帖子ID倒序
先来个redis操作类
/**
* redis操作类
* author by hu.chen 20191110
* Class RedisDemo
*/
class RedisDemo
{
private static $instance;
private $objRedis;
private $redisAddress = '127.0.0.1';
private $redisPort = '6379';
private $redisPassword = 'www.huchen.net';
private $redisDbName = 16;
private $redisPrefix = 'JJMS';
private $key = 'List';
/**
* 构造方法 初始化redis对象
* JJWXCRedisDemo constructor.
* @param $config
*/
private function __construct($config)
{
if (!empty($config['redisAddress'])){
$this->redisAddress = $config['redisAddress'];
}
if (!empty($config['redisPassword'])){
$this->redisPassword = $config['redisPassword'];
}
if (!empty($config['redisPort'])){
$this->redisPort = $config['redisPort'];
}
if (!empty($config['redisDbName'])){
$this->redisDbName = $config['redisDbName'];
}
if (!empty($config['redisPrefix'])){
$this->redisPrefix = $config['redisPrefix'];
}
$this->objRedis = new Redis();
//链接redis
try{
$connect = $this->objRedis->connect($this->redisAddress,$this->redisPort,30);
}catch (Exception $e) {
echo $e->getMessage();exit;
}
//认证密码
try{
$auth = $this->objRedis->auth($this->redisPassword);
}catch (Exception $e) {
echo $e->getMessage();exit;
}
//选择数据库
$this->objRedis->select($this->redisDbName);
}
/**
* 单例
* @param $config
* @return JJWXCRedisDemo
*/
public static function getInstance($config){
if(self::$instance == NULL){
self::$instance = new self($config);
}
return self::$instance;
}
/**
* 添加hash数据
* @param $id
* @param