我在处理大型Laravel项目和Redis存储时遇到问题。我们将会话存储在Redis中。我们已经有28GB的RAM。但是,它仍然可以相对快地运行到极限,因为我们的搜索引擎机器人点击率很高(每天超过250,000)。
是否有任何优雅的方法可以完全禁用bot会话?我已经实现了自己的会话中间件,如下所示:
<?php
namespace App\Http\Middleware;
use App\Custom\System\Visitor;
class StartSession extends \Illuminate\Session\Middleware\StartSession
{
protected function getSessionLifetimeInSeconds()
{
if(Visitor::isBot()) {
return 1;
}
return ($this->manager->getSessionConfig()['lifetime'] ?? null) * 60;
}
protected function sessionIsPersistent(array $config = null)
{
if(Visitor::isBot()) {
return false;
}
$config = $config ?: $this->manager->getSessionConfig();
return ! in_array($config['driver'], [null, 'array']);
}
}
这是我检测机器人的功能:
public static function isBot()
{
$exceptUserAgents = [
'Googlebot',
'Bingbot',
'Yahoo! Slurp',
'DuckDuckBot',
'Baiduspider',
'YandexBot',
'Sogou',
'facebot',
'ia_archiver',
];
if(!request()->header('User-Agent') || !str_contains(request()->header('User-Agent'), $exceptUserAgents)) {
return false;
}
return true;
}
不幸的是,这似乎不起作用。有人在这里有小费或经验吗?非常感谢你!
答案 0 :(得分:3)
这就是我自己解决此问题的方式。
包括使用composer的漫游器检测程序包。我用了这个:https://github.com/JayBizzle/Crawler-Detect
composer require jaybizzle/crawler-detect
创建一个新的中间件类
namespace App\Http\Middleware; class NoSessionForBotsMiddleware { public function handle($request, \Closure $next) { if ((new \Jaybizzle\CrawlerDetect\CrawlerDetect)->isCrawler()) { \Config::set('session.driver', 'array'); } return $next($request); } }
Kernel
类中protected $middlewareGroups = [ 'web' => [ // .. NoSessionForBotsMiddleware::class, StartSession::class, // .. ], // .. ];
答案 1 :(得分:1)
您的问题可能是您没有正确识别机器人,因此提供相应的代码会有所帮助。
特定于编写禁用会话的中间件,最好将会话驱动程序更改为array
驱动程序,因为该驱动程序不会持久化会话,而不是在运行时更改实际会话驱动程序的配置。
<?php
namespace App\Http\Middleware;
use App\Custom\System\Visitor;
use Illuminate\Support\Facades\Config;
class DiscardSessionIfBot
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Visitor::isBot()) {
Config::set('session.driver', 'array');
}
return $next($request);
}
}