Thinkphp在添加、修改、删除数据时,自动更新Cache缓存的方法

thinkphp使用缓存可以有效提升系统性能,节省数据库操作和内存开支。

简单示例:

<?php
use think\Cache;

if (Cache::has('user_data')) {
    $users = Cache::get('user_data')
} else {
    $users = User::where('status', 1)->select();
    // 缓存用户数据5分钟
    Cache::set('user_data', $users, 300);
}

上面的代码还可以简化成:

<?php
use think\Cache;

$users = Cache::remember('user_data', function(){
    return User::where('status', 1)->select();
},300);

问题来了,上述缓存的时间是5分钟,如果在这5分钟内对user用户表执行了添加、修改、删除等操作,你会发现缓存没有发生改变,网站不能及时获取最真实的数据。那应该怎么办呢?

解决方法:

在执行完添加、修改、删除等操作时,调用Cache::clear(),如下:

<?php
use think\Cache;

public function add(){		
    try{
		User::create([
			'name'   => "tom",
			'age'  => 18
		]);
	} catch (\Exception $e) {
		$this->error('添加失败');
	}
    //清理缓存
	Cache::clear();
	$this->success('添加成功');
} 

补充:清除缓存、模版缓存和日志缓存的方法

namespace app\cache\controller;
use think\Controller;
use think\Cache;

	//清除模版缓存不删除cache目录;
	public function clear_sys_cache()
	{
		Cache::clear();
		$this->success('清除成功', 'Index/index');
	}

	//清除模版缓存但不删除temp目录;
	public function clear_temp_ahce()
	{
		$path = glob(TEMP_PATH . '*.php');
		array_map('unlink', $path);
        //rmdir(TEMP_PATH .'temp/');//删除temp目录
		$this->success('清除成功', 'Index/index');
	}

	//清除日志缓存并删出log空目录;
	public function clear_log_chache()
	{
		$path = glob(LOG_PATH . '*');
		foreach ($path as $item) {
			//dump(glob($item .DS. '*.log'));
			array_map('unlink', glob($item . DS . '*.log'));
			rmdir($item);
		}
		$this->success('清除成功', 'Index/index');
	}

猜你喜欢

转载自blog.csdn.net/qq15577969/article/details/114281835
今日推荐