laravel缓存 怎么判断redis服务器是不是挂掉

我使用reids作为缓存,每次查询redis中是不是有缓存,没有缓存就在数据库里面查一下,保存半小时。但是如果没打开redis或者redis挂掉的情况下,网页就无法正常打开了。
能不能判断一下reids是不是存在,当reids挂掉的情况下,可以直接读取数据库来保证页面还能正常运行。
用的是阿里的reids,单机版。是不是我多虑了,不用考虑redis挂掉的情况

 if (Cache::tags('site')->has($county_key)) {
            $$county_info = Cache::tags('site')->get($county_key);
        }else{
            $County = new County;
            $County_info = $County->getCountyInfo($is_city_info[$id]['city_id']);
            $county_info = json_encode($County_info);
            //如果redis挂掉的话,这里就回发生错误,页面无法正常打开
            Cache::tags('site')->add($county_key,$$county_info,14000);
        }

2个回答

你是对的,无论 get put delete 都要先判断 redis 的 connection 状态,我用的 java jedis ,试过redis 停掉以后项目就挂了。
我想修改jedis 让 connection 挂掉时,不抛出异常,但是不知道怎么通知 mybatis 去 db 查询。

gavin_gwt
gavin_gwt 最后怎么做的
2 年多之前 回复

redis做缓存的流程就是先读redis,但不能读取的时候就去数据库读取数据,并更新redis。

gavin_gwt
gavin_gwt 我就是先读redis,如果缓存里面没有才去数据库里面读取,再去更新reids,这个流程不对么
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
为什么Redis缓存驱动程序不能在Laravel中为我工作?

<div class="post-text" itemprop="text"> <p>Specifically, <code>Cache::put</code> doesn't seem to be working for me. I've set the following items in my .env file, and I have the predis/predis library installed.</p> <pre><code># redis + cache CACHE_DRIVER=redis REDIS_HOST=127.0.0.1 REDIS_PORT=6379 REDIS_CACHE_DB=1 </code></pre> <p>I have left the config files unmodified (they are using the above values.)</p> <p>Then in my php code I have:</p> <pre><code>if (!empty($request-&gt;header('Authorization'))) { $token = str_replace('Bearer ', '', $request-&gt;header('Authorization')); // first check the cache for the user id Log::debug("attempting to get user id for token {$token} from cache"); $response = json_decode(Cache::get($token, function() use ($request, $token) { Log::debug("token not found in cache, fetching"); $auth_server = config('auth.oauth.auth_server'); try { $response = $this-&gt;http-&gt;get("{$auth_server}/api/verify", [ 'headers' =&gt; [ 'Authorization' =&gt; $request-&gt;header('Authorization'), 'Accept' =&gt; 'Application/json' ] ]); } catch (ClientException $e) { $response = $e-&gt;getResponse(); $json_response = json_decode((string)$response-&gt;getBody()); $json_response-&gt;code = $response-&gt;getStatusCode(); return $json_response; } $response_body = $response-&gt;getBody()-&gt;getContents(); $json = json_decode($response_body); if ($json-&gt;success) { Log::debug("adding cache with key $token and value $response_body"); Cache::put($token, $response_body); return $response_body; } return null; })); } </code></pre> <p>I have issued a <code>redis-cli monitor</code> command in the command line and while I can definitely see that it attempts to get from the cache, I never see a call to put things in the cache. I am currently on Laravel 5.7 if that makes any difference..</p> </div>

如何在Laravel 5中使用redis为多租户多数据库架构应用程序执行排队和缓存?

<div class="post-text" itemprop="text"> <p>I am working on a multi-tenant multi-database architecture application using Laravel which basically means that every tenant in the application has their own database, own sets of users, resources and so on.</p> <p>Now I am trying to implement queues and caching in the application, then I am trying to use redis for that. A sample code looks like this:</p> <pre><code>$mailer-&gt;send('emails.welcome', ['user' =&gt; $user], function ($message) use ($user) { $message-&gt;from("admin@admin.com", "Admin"); $message-&gt;to($user-&gt;email, $user-&gt;first_name)-&gt;subject("Welcome!"); }); </code></pre> <p>This is to send a welcome email to user sign-up. But the queuing is storing all the queues in the same database in the same Redis instance, different tenant emails will get mixed up as far as I can tell.</p> <p>How do I hook into Laravel 5 and change the queue behavior to either store the jobs for each tenant in a separate database or store extra meta-information about the tenant a particular job belongs to? And then also how would I tell Laravel to parse that extra meta-information and connect to the right tenant database before proceeding with the job?</p> </div>

Laravel Mockup Cache Redis

<div class="post-text" itemprop="text"> <p>I have problem with mockup Redis and tags cache I get error Error: Call to a member function get() on null</p> <pre><code>$cache = Cache::shouldReceive('store-&gt;redis')-&gt;shouldReceive('tags') -&gt;once()-&gt;with('tripUpdate') -&gt;shouldReceive('get') -&gt;once()-&gt;with('trip_update_' . 1) -&gt;andReturn(json_encode([])); </code></pre> <p>I want try mockup this code :</p> <pre> $tag = Cache::store("redis")-&gt;tags("tripUpdate"); $tripUpdateCache = $tag-&gt;get('trip_update_' . $tripId); </pre> </div>

如何使Laravel广播/ websockets与Redis Cluster协同工作

<div class="post-text" itemprop="text"> <p>I got a Redis Cluster server which I created by following this <a href="https://redis.io/topics/cluster-tutorial#creating-the-cluster" rel="nofollow noreferrer">tutorial</a>. </p> <p>This is what my database/config.php setup looks like (see details <a href="https://stackoverflow.com/questions/56497809/how-to-make-laravel-work-with-redis-cluster-on-aws">here</a>):</p> <pre><code>'redis' =&gt; [ 'client' =&gt; 'predis', 'cluster' =&gt; true, 'options' =&gt; [ 'cluster' =&gt; 'redis', 'parameters' =&gt; [ 'host' =&gt; env('REDIS_DEFAULT_HOST', '127.0.01'), 'password' =&gt; env('REDIS_PASSWORD', null), 'port' =&gt; env('REDIS_DEFAULT_PORT', 6379), 'database' =&gt; 0, ], ], 'clusters' =&gt; [ 'default' =&gt; [ 'host' =&gt; env('REDIS_DEFAULT_HOST', '127.0.01'), 'password' =&gt; env('REDIS_PASSWORD', null), 'port' =&gt; env('REDIS_DEFAULT_PORT', 6379), 'database' =&gt; 0, ], 'jobs' =&gt; [ 'host' =&gt; env('REDIS_JOBS_HOST', '127.0.01'), 'password' =&gt; env('REDIS_PASSWORD', null), 'port' =&gt; env('REDIS_JOBS_PORT', 6379), 'database' =&gt; 0, ], 'content' =&gt; [ 'host' =&gt; env('REDIS_CONTENT_HOST', '127.0.01'), 'password' =&gt; env('REDIS_PASSWORD', null), 'port' =&gt; env('REDIS_CONTENT_PORT', 6379), 'database' =&gt; 0, ], 'options' =&gt; [ 'cluster' =&gt; 'redis' ], ] ] </code></pre> <p>and what my config/broadcasting.php looks like:</p> <pre><code>&lt;?php return [ /* |-------------------------------------------------------------------------- | Default Broadcaster |-------------------------------------------------------------------------- | | This option controls the default broadcaster that will be used by the | framework when an event needs to be broadcast. You may set this to | any of the connections defined in the "connections" array below. | */ 'default' =&gt; env('BROADCAST_DRIVER', 'redis'), /* |-------------------------------------------------------------------------- | Broadcast Connections |-------------------------------------------------------------------------- | | Here you may define all of the broadcast connections that will be used | to broadcast events to other systems or over websockets. Samples of | each available type of connection are provided inside this array. | */ 'connections' =&gt; [ 'pusher' =&gt; [ 'driver' =&gt; 'pusher', 'key' =&gt; env('PUSHER_KEY'), 'secret' =&gt; env('PUSHER_SECRET'), 'app_id' =&gt; env('PUSHER_APP_ID'), ], 'redis' =&gt; [ 'driver' =&gt; 'redis', 'connection' =&gt; 'default', ], 'log' =&gt; [ 'driver' =&gt; 'log', ], ], ]; </code></pre> <p>when i reach this part in my code when i want to publish an event in redis:</p> <pre><code> // Dispatch an event indicates order status has been changed. event(new OrderStatusChanged($order-&gt;id, OrderActionsConstants::INCOMPLETE_CART)); </code></pre> <p>I get this error:</p> <pre><code>Cannot use 'PUBLISH' with redis-cluster. </code></pre> <p>with this stack trace</p> <pre><code>[2019-06-10 17:05:06] local.ERROR: 0 /Users/Shared/dev/php/toters-api/vendor/predis/predis/src/Connection/Aggregate/RedisCluster.php(550): Predis\Connection\Aggregate\RedisCluster-&gt;getConnection(Object(Predis\Command\PubSubPublish)) 1 /Users/Shared/dev/php/toters-api/vendor/predis/predis/src/Connection/Aggregate/RedisCluster.php(593): Predis\Connection\Aggregate\RedisCluster-&gt;retryCommandOnFailure(Object(Predis\Command\PubSubPublish), 'executeCommand') 2 /Users/Shared$dev/php/toters-api/vendor/predis/predis/src/Client.php(331): Predis\Connection\Aggregate\RedisCluster-&gt;executeCommand(Object(Predis\Command\PubSubPublish)) 3 /Users/Shared/dev/php/toters-api/vendor/predis/predis/src/Client.php(314): Pre$is\Client-&gt;executeCommand(Object(Predis\Command\PubSubPublish)) 4 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(72): Predis\Client-&gt;__call('publish', Array) 5 /Users/Shared/de$/php/toters-api/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(84): Illuminate\Redis\Connections\Connection-&gt;command('publish', Array) 6 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/$roadcasting/Broadcasters/RedisBroadcaster.php(99): Illuminate\Redis\Connections\Connection-&gt;__call('publish', Array) 7 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php(48): Illumin$te\Broadcasting\Broadcasters\RedisBroadcaster-&gt;broadcast(Array, 'order.status', '{"event":"order...') 8 [internal function]: Illuminate\Broadcasting\BroadcastEvent-&gt;handle(Object(Illuminate\Broadcasting\Broadcasters\RedisBroadcaster)) $ /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array) 10 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Container/BoundMetho$.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}() 11 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Ob$ect(Illuminate\Foundation\Application), Array, Object(Closure)) 12 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(539): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundatio$\Application), Array, Array, NULL) 13 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container-&gt;call(Array) 14 /Users/Shared/dev/php/toters-api/vendor/laravel/frame$ork/src/Illuminate/Pipeline/Pipeline.php(114): Illuminate\Bus\Dispatcher-&gt;Illuminate\Bus\{closure}(Object(Illuminate\Broadcasting\BroadcastEvent)) 15 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipe$ine.php(102): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Broadcasting\BroadcastEvent)) 16 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pip$line\Pipeline-&gt;then(Object(Closure)) 17 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(42): Illuminate\Bus\Dispatcher-&gt;dispatchNow(Object(Illuminate\Broadcasting\BroadcastEvent), fal$e) 18 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(69): Illuminate\Queue\CallQueuedHandler-&gt;call(Object(Illuminate\Queue\Jobs\SyncJob), Array) 19 /Users/Shared/dev/php/toters-api/vendor/la$avel/framework/src/Illuminate/Queue/SyncQueue.php(42): Illuminate\Queue\Jobs\Job-&gt;fire() 20 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(42): Illuminate\Queue\SyncQueue-&gt;push(Object(Illuminate$Broadcasting\BroadcastEvent), '', NULL) 21 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php(128): Illuminate\Queue\Queue-&gt;pushOn(NULL, Object(Illuminate\Broadcasting\BroadcastEve$t)) 22 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(270): Illuminate\Broadcasting\BroadcastManager-&gt;queue(Object(App\Events\OrderStatusChanged)) 23 /Users/Shared/dev/php/toters-api/vend$r/laravel/framework/src/Illuminate/Events/Dispatcher.php(193): Illuminate\Events\Dispatcher-&gt;broadcastEvent(Object(App\Events\OrderStatusChanged)) 24 /Users/Shared/dev/php/toters-api/vendor/laravel/framework/src/Illuminate/Foundation/he$pers.php(446): Illuminate\Events\Dispatcher-&gt;dispatch('App\\Events\\Orde...') 25 /Users/Shared/dev/php/toters-api/app/Repositories/Orders/AppOrdersRepo.php(107): event(Object(App\Events\OrderStatusChanged)) </code></pre> <p>How do I fix this?</p> </div>

使用Redis和Laravel使用密码

<div class="post-text" itemprop="text"> <p>I've got an app written using Laravel. I've been using Redis when developing locally. I've now moved my project onto AppFog which has a redis service running. It seems though that they require a password (which is supplied), but I'm not sure how to add a password to the redis config in database.php.</p> <p>When I try to use redis without the password I get "Redis error: operation not permitted". A quick look and it seems that's what happens when a password isn't supplied.</p> <p>Anyone know how to supply a password when connecting to a Redis DB using Laravel?</p> </div>

使用redis服务器和主管同时运行多个laravel队列作业

<div class="post-text" itemprop="text"> <p>I am working on queue job in Laravel v4.2 project and I have five queue worker to perform different type of jobs in queues and each worker has more than 500 jobs at the same time. For queue job I am using redis server and supervisor to process automatically. Now problem that I am facing is that supervisor process one job at a time and another job process after completing the first queue job. Now I want to process more than one job at the same time and for this purpose I search on google and forums too but failed to find correct answer below is my command that I am running to run queue jobs through supervisor</p> <pre><code>command=php /home/rizwan/php/webservices/local/artisan queue:listen --queue=notificationQueue,lowQueue --tries=1 command=php /home/rizwan/php/Fayvo/favyo_webservices/local/artisan queue:listen --tries=1 </code></pre> <p>if I remove priority param from command then queue jobs does not process which is wrong and if I add it then it process notificationQueue jobs first and then lowQueue jobs after processing all the jobs of notificationQueue jobs but I want to process both jobs at same time.</p> <p>supervisor configuration</p> <pre><code>redirect_stderr=true autostart=true autorestart=true numprocs = 4 process_name = %(program_name)s%(process_num)s user=rizwan </code></pre> </div>

redis不是数据库吗?什么大家都用redis做缓存?

redis不是数据库吗?什么大家都用redis做缓存? redis不是数据库吗?什么大家都用redis做缓存? redis不是数据库吗?什么大家都用redis做缓存?

尝试在laravel上发布到redis时,在null上调用成员函数publish()

<div class="post-text" itemprop="text"> <p>I am trying to publish stuff to redis but I get this error:</p> <pre><code>Call to a member function publish() on null. </code></pre> <p>Not sure whats going on. This is my code. Works well on the local environment but on the server the above error message shows. I have the following code in a controller. The website is hosted on windows azure appservice. I have also installed the predis/predis dependency.</p> <pre><code>$redis = Redis::connection(6380)-&gt;publish('test-channel', json_encode(['foo' =&gt; 'bar'])); </code></pre> <p>Am I not connecting to redis or something?</p> </div>

laravel redis socket.io广播问题

事件中触发的广播 ``` public function broadcastOn() { return new PrivateChannel( 'say-hello.1' ); } ``` BroadcastsProvider //即使以下代码删了 客户端也能收到内容 ``` Broadcast::channel( 'say-hello.{orderId}' , function ( $user,$orderId ) { return false;//这里我不管是返回true 还是false 客户端都能收到内容 } , [ 'guards' => [ 'admin' ] ] ); ``` 客户端JS内容 ``` var options = { auth: { headers: {'Authorization': 'Bearer eyJ0eX....'} } } var socket = io('https://api.xx.net' + ':6001', options); socket.emit('subscribe', { channel: 'private-say-hello.1', auth: options.auth }).on('App\\Containers\\Order\\Events\\Events\\CreateTakeawayOrderEvent', function (channel, data) { console.log(data);//即使 不传token 这里也能打印数据 }); ```

Redis+MongoDB 服务器端高速缓存

最近想使用Redis数据库当做Windows服务器上的一个高速缓存,我现在的思路是客户端向Redis数据库请求数据,如果Redis中已经缓存的有这些数据,就直接反馈给客户端,如果没有,Redis再向MongoDB中调用数据,将数据存入Redis,之后在发送给客户端,不知道这种思路可否行得通,还请各位大神多多指点。

使用redis缓存替代mybatis系统缓存的优点

为什么要使用redis替代mubatis系统缓存 ,使用redis缓存替代mybatis系统缓存的优点

Laravel Queue(REDIS)批量大小

<div class="post-text" itemprop="text"> <p>Is there a way to change batch size of processed ID's from redis by worker? </p> <p>I'm using Redis as a queue for mysql, due to the big data import into mysql, with Laravel 5.3.</p> <p>Another thing is, that I presume, it is not a good idea to overflow php here, although, I've changed php.ini memory to 512MB.</p> <p>Due to the nature of redis being, as I understand, list of FIFO's in this case, is there a way to run multiple workers at once? (This could be another quesion, sorry about that)</p> <p>Feel free to push me into another direction, cause I'm open to any suggestions.</p> </div>

PhpRedis错误异常unset中的非法偏移类型或Php致命错误php调用未定义方法share() - Laravel 5.4

<div class="post-text" itemprop="text"> <p>I am trying to get started with PhpRedis in Laravel 5.4 and in this link: <a href="https://github.com/laravel/framework/commit/1a1969b6e6f793c3b2a479362641487ee9cbf736" rel="nofollow noreferrer">https://github.com/laravel/framework/commit/1a1969b6e6f793c3b2a479362641487ee9cbf736</a> it says to change share() function to singleton() as share is no more supported in Laravel 5.4. </p> <p>By default (in the process of installing redis) I get this error:</p> <pre><code>PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::share() in ...\vendor\vetruvet\laravel-phpredis\src\Vetruvet\PhpRedis\PhpRedisServiceProvider.php on line 12 </code></pre> <p>If I change share() to singledton() in PhpRedisServiceProvider.php I get error:</p> <pre><code>Error Exception Illegal offset type in unset </code></pre> <p>If changing share to singleton is correct then how to fix illegal offset?</p> <p><strong>New Updated error</strong></p> <p>PHP Fatal error: Class 'Illuminate\Redis\Database' not found in </p> <pre><code>...\vendor\vetruvet\laravel-phpredis\src\Vetruvet\PhpRedis\Database.php on line 7 [Symfony\Component\Debug\Exception\FatalErrorException] Class 'Illuminate\Redis\Database' not found </code></pre> <p><strong>Composer.json</strong></p> <pre><code>"require": { "php": "&gt;=5.6.4", "laravel/framework": "5.4.*", "laravel/tinker": "~1.0", "laravelcollective/html": "~5.0", "laracasts/utilities": "~2.0", "guzzlehttp/guzzle": "~5.3|~6.0", "vetruvet/laravel-phpredis": "1.*" }, </code></pre> <p><strong>app.php</strong></p> <pre><code>Illuminate\Queue\QueueServiceProvider::class, //Illuminate\Redis\RedisServiceProvider::class, Vetruvet\PhpRedis\PhpRedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, </code></pre> <p><strong>Aliases in app.php</strong></p> <pre><code>//'Redis' =&gt; Illuminate\Support\Facades\Redis::class, 'LRedis' =&gt; Illuminate\Support\Facades\Redis::class, </code></pre> <p><strong>PhpRedisServiceProvider.php</strong></p> <pre><code>&lt;?php namespace Vetruvet\PhpRedis; use Illuminate\Support\ServiceProvider; class PhpRedisServiceProvider extends ServiceProvider { protected $defer = true; public function register() { //$this-&gt;app['redis'] = $this-&gt;app-&gt;share(function($app) { $this-&gt;app-&gt;singleton('redis', function ($app) { return new Database($app['config']['database.redis']); }); } public function provides() { return array('redis'); } } </code></pre> <p><strong>PhpRedis\Database.php</strong></p> <pre><code>&lt;?php namespace Vetruvet\PhpRedis; use \Redis; class Database extends \Illuminate\Redis\Database { /** * Create a new aggregate client supporting sharding. * * @param array $servers * @return array */ protected function createAggregateClient(array $servers) { $options = array( 'lazy_connect' =&gt; true, 'pconnect' =&gt; false, 'timeout' =&gt; 0, ); $cluster = array(); foreach ($servers as $key =&gt; $server) { if ($key === 'cluster') continue; $host = empty($server['host']) ? '127.0.0.1' : $server['host']; $port = empty($server['port']) ? '6379' : $server['port']; $serializer = Redis::SERIALIZER_NONE; if (!empty($server['serializer'])) { if ($server['serializer'] === 'none') { $serializer = Redis::SERIALIZER_PHP; } else if ($server['serializer'] === 'igbinary') { if (defined('Redis::SERIALIZER_IGBINARY')) { $serializer = Redis::SERIALIZER_IGBINARY; } else { $serializer = Redis::SERIALIZER_PHP; } } } $cluster[$host.':'.$port] = array( 'prefix' =&gt; empty($server['prefix']) ? '' : $server['prefix'], 'database' =&gt; empty($server['database']) ? 0 : $server['database'], 'serializer' =&gt; $serializer, ); if (isset($server['persistent'])) { $options['pconnect'] = $options['pconnect'] &amp;&amp; $server['persistent']; } else { $options['pconnect'] = false; } if (!empty($server['timeout'])) { $options['timeout'] = max($options['timeout'], $server['timeout']); } } $ra = new RedisArray(array_keys($cluster), $options); foreach ($cluster as $host =&gt; $options) { $redis = $ra-&gt;_instance($host); $redis-&gt;setOption(Redis::OPT_PREFIX, $options['prefix']); $redis-&gt;setOption(Redis::OPT_SERIALIZER, $options['serializer']); $redis-&gt;select($options['database']); } return array('default' =&gt; $ra); } /** * Create an array of single connection clients. * * @param array $servers * @return array */ protected function createSingleClients(array $servers) { $clients = array(); foreach ($servers as $key =&gt; $server) { if ($key === 'cluster') continue; $redis = new Redis(); $host = empty($server['host']) ? '127.0.0.1' : $server['host']; $port = empty($server['port']) ? '6379' : $server['port']; $timeout = empty($server['timeout']) ? 0 : $server['timeout']; if (isset($server['persistent']) &amp;&amp; $server['persistent']) { $redis-&gt;pconnect($host, $port, $timeout); } else { $redis-&gt;connect($host, $port, $timeout); } if (!empty($server['prefix'])) { $redis-&gt;setOption(Redis::OPT_PREFIX, $server['prefix']); } if (!empty($server['database'])) { $redis-&gt;select($server['database']); } if (!empty($server['serializer'])) { $serializer = Redis::SERIALIZER_NONE; if ($server['serializer'] === 'php') { $serializer = Redis::SERIALIZER_PHP; } else if ($server['serializer'] === 'igbinary') { if (defined('Redis::SERIALIZER_IGBINARY')) { $serializer = Redis::SERIALIZER_IGBINARY; } else { $serializer = Redis::SERIALIZER_PHP; } } $redis-&gt;setOption(Redis::OPT_SERIALIZER, $serializer); } $clients[$key] = $redis; } return $clients; } } </code></pre> </div>

用redis在laravel中排队

<div class="post-text" itemprop="text"> <p>I'm having trouble with an application where i do a lot of api calls in the backend. Because of this the application gets a timeout error. </p> <p>Someone suggested I should use Queues. I have tried to do so whit redis. The function goes in the job and uses the handler but I expected the page to load with the data I give it without the data from the api while teh api-call is going through on the background. Instead it just goed through like when i hadn't used the queue. I tried to follow a tutorial to do this but they weren't doing exactly the same and I couldn't adjust it so it would work for me.</p> <p>For info about what i do in the job. I get comments out a csv and the I use the numbers in the comments to call to the api and i get a json of like 8-10 fields. I need to call the api about 650 times so it takes o long when i want to save the data to the database. I use one insert at a time to usee "caching" so i wont do the same call twice.</p> <p>This is the controller where I call on the job.</p> <pre><code>class ImportController extends Controller { public function checkErrors(Request $request) { $this-&gt;checkAgainstDocuments($csv_id); $supplierErrorIds=$this-&gt;checkSupplierErrors($parameters, $company , $csv_id); $timesheetErrors=TsData::whereIn('id', $supplierErrorIds)-&gt;sortable()-&gt;paginate(20); return view('show_errors', compact('timesheetErrors', 'company', 'csv_id')); } public function checkAgainstDocuments($csv_id) { GetFromDocumentsAPI::dispatch($csv_id)-&gt;delay(now()-&gt;addMinutes(10)); } } </code></pre> <p>This is the job I use:</p> <pre><code>class GetFromDocumentsAPI implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $csv_id; /** * Create a new job instance. * * @return void */ public function __construct($csv_id) { // $this-&gt;csv_id=$csv_id; } /** * Execute the job. * * @return void */ public function handle() { $comments = TsData::select('id', 'comments')-&gt;where('csv_id', $this-&gt;csv_id)-&gt;get()-&gt;toArray(); $commentIDs = array(); foreach ($comments as $comment) { preg_match_all('/(\d{5,})/', $comment['comments'], $out, PREG_PATTERN_ORDER); foreach ($out as $item) { $commentIDs[$comment['id']] = $item; } } $commentIDs = array_filter($commentIDs); $apiKey=config('app.apiKey'); $documentsResponse = array(); Issue::truncate(); $arrayTest=[]; foreach ($commentIDs as $key =&gt; $commentID) { foreach ($commentID as $item) { $issue = Issue::where('id', $item)-&gt;first(); if ($issue === null) { try { $url = file_get_contents('https://documents.calibrate.be/issues/' . $item . '.json?key=' . $apiKey); $json = json_decode($url, true); } catch (Exception $e) { echo 'Caught exception: ', $e-&gt;getMessage(), " "; } $issue = Issue::Create(['id'=&gt;$item, 'name'=&gt;$json['issue']['subject'], 'projectId'=&gt;$json['issue']['project']['id'], 'priority'=&gt;$json['issue']['priority']['id']]); } } } </code></pre> <p>}</p> <p>config/queue.php</p> <pre><code>'default' =&gt; env('QUEUE_DRIVER', 'redis'), 'redis' =&gt; [ 'driver' =&gt; 'redis', 'connection' =&gt; 'default', 'queue' =&gt; env('REDIS_QUEUE', 'default'), 'retry_after' =&gt; 90, 'block_for' =&gt; null, ], </code></pre> </div>

mybatis 二级缓存集成 redis的问题

mybatis 集成了二级缓存,正常都是可以使用的,但是把redis 服务停了, 查询就不好使了,报异常 ``` nested exception is org.apache.ibatis.exceptions.PersistenceException: \n### Error querying database. Cause: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused (Connection refused)\n### Cause: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused (Connection refused) ``` 个人理解,缓存不好使,正常来说不应该查询数据库么?求大牛给指导一下!

redis跟ehcache搭配使用怎么解决脏数据的问题

ehcache 作一级缓存,redis作二级缓存,怎么解决脏数据问题 如果服务器A和服务器B都在本地ehcache缓存中缓存了同一个数据X,若服务器A对X修改为了Y,那么修改后的结果Y会缓存在服务器A的ehcache缓存和redis中心缓存中,但是此时服务器B取到的这个数据会是X还是Y呢?服务器A对X数据进行修改后,redis中心缓存不会主动将修改后的值Y推送到各个服务器吗?

redis查找和更新的缓存问题

1.首先先进行查找uuid为123的用户 ``` @GetMapping("/{uuid}") public User get(@PathVariable String uuid) { return userService.findByUuid(uuid); } @Cacheable(value = "userInfo", key = "'findByUuid-' + #uuid") @Override public User findByUuid(String uuid) { return userDao.findOne(uuid); } ``` 能确保uuid为123的用户查找得出来而且查找到的用户也存入缓存.(多查找几次控制台也只显示一次的sql语句) 2.更新uuid为123的用户 ``` @PutMapping("/{uuid}") public String update(@PathVariable String uuid,@RequestBody User updateUser){ User user = userService.findByUuid(uuid); user.setUserName(updateUser.getUserName()); user.setPassword(updateUser.getPassword()); user.setAge(updateUser.getAge()); user.setPhone(updateUser.getPhone()); userService.save(user); return "success"; } @CacheEvict(value = "userInfo", key = "'findByUuid-' + #user.getUuid()") @Override public User save(User user) { return userDao.save(user); } ``` 更新时执行却又执行了select ,按道理来说findByUuid(123)应该被存入缓存,而不会打印select 语句才对啊. 以下是更新uuid为123时控制台打印的语句 ``` Hibernate: select user0_.uuid as uuid1_0_0_, user0_.age as age2_0_0_, user0_.password as password3_0_0_, user0_.phone as phone4_0_0_, user0_.user_name as user_nam5_0_0_ from user user0_ where user0_.uuid=? Hibernate: update user set age=?, password=?, phone=?, user_name=? where uuid=? ```

查询数据放入了redis中缓存,怎么查看缓存的数据呀

作为新手,尝试读取数据的时候缓存数据在redis中,已经放成功了, 去redis中找没找到,要怎么查看我redis中放了的缓存数据。 谢谢大神指导。

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐