Laravel 5.0, env() returns null during concurrent

2019-06-26 17:10发布

问题:

The problem is that when I try to get a config variable using env('setting') or \Config::get('setting'), sometimes it returns null.

For the testing reason I created a simple route:

Route::get('/test', function () {
    $env = env('SETTING');
    if (!$env) {
        \Log::warning('test', [$env]);
    }
});

Then I used apache benchmark. And the results were like this:

  • Calling only one request at a time (ab -n 100 -c 1 http://localhost/test) there were no problem, no records in the log file
  • Calling with 10 concurrent requests (ab -n 100 -c 10 http://localhost/test) I got about 20 lines like this: [2015-06-22 14:19:48] local.WARNING: test [null]

Does anybody know, what can be the problem? Is there something missing in my configuration or in php settings?

回答1:

This is a know bug in dotenv package - see the discussion here https://github.com/laravel/framework/issues/8191



回答2:

This happen to me as well. My workaround is in your config/app.php you have to add this:

'setting' => env('SETTING'),

Then when you want to get the setting config you have to do this:

$env = config('app.setting');