Laravel: How to Check Redis Availability? - redis

How can i check the availability of Redis connection in Laravel 5.4. I tried below code, but getting an exception with ping line. How can i do, if Redis is not connected than do something else to avoid exception?
No connection could be made because the target machine actively
refused it. [tcp://127.0.0.1:6379]
use Redis;
class SocketController extends Controller
{
public function sendMessage(){
$redis = Redis::connection();
if($redis->ping()){
print_r("expression");
}
else{
print_r("expression2");
}
}
}
Also tried this:
$redis = Redis::connection();
try{
$redis->ping();
} catch (Exception $e){
$e->getMessage();
}
But unable to catch exception

if you are using predis , then it will throw Predis\Connection\ConnectionException
Error while reading line from the server. [tcp://127.0.0.1:6379] <--when redis is not connected
so catch that Exception, you will get your redis is connected or not .
use Illuminate\Support\Facades\Redis;
public function redis_test(Request $request){
try{
$redis=Redis::connect('127.0.0.1',3306);
return response('redis working');
}catch(\Predis\Connection\ConnectionException $e){
return response('error connection redis');
}

<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class ConnectionChecker
{
public static function isDatabaseReady($connection = null)
{
$isReady = true;
try {
DB::connection($connection)->getPdo();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
public static function isRedisReady($connection = null)
{
$isReady = true;
try {
$redis = Redis::connection($connection);
$redis->connect();
$redis->disconnect();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
}
I created a helper class to check redis and db connection

Make sure redis is installed
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
To test that your service is functioning correctly, connect to the Redis server with the command-line client:
redis-cli
In the prompt that follows, test connectivity by typing:
ping
You should see:
Output
PONG
Install Laravel dependencies
composer require predis/predis
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04
https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04

In your constructor you can check redis status connection like this:
/**
* RedisDirectGeoProximity constructor.
* #throws RedisConnectionException
*/
public function __construct()
{
try
{
$this->redisConnection = Redis::connection('default');
}
catch ( Exception $e )
{
throw new RedisConnectionException([
'message' => trans('messages.redis.fail'),
'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
]);
}
}
and in your exception :
namespace App\Exceptions\Redis;
/**
* Class RedisConnectionException
* #package App\Exceptions\Redis
*/
class RedisConnectionException extends \Exception
{
/**
* RedisConnectionException constructor.
* #param array $options
*/
public function __construct(array $options = [])
{
parent::__construct($options);
}
}

please try with catch (\Exception $e) incl. backslash

Related

I got an error during database migration in laravel9

catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
}
1 C:\wamp64\www\laravelProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDOException::("SQLSTATE[HY000] [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
")
2 C:\wamp64\www\laravelProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDO::__construct("mysql:host=127.0.0.1;port=3308;dbname=laravelproject", "root", "", [])
use Illuminate\Support\Facades\Schema; <-------------------------ADD THIS
public function boot()
{
Schema::defaultStringLength(191); <-------------------------ADD THIS
}
}
This is the final code.

Assigning error to api in try and catch transaction

i have the following code (assume transaction is working properly)
try{
if (!$model->save() {
$return = Yii::t('app/job', 'JOB_NOT_FOUND');
trow new \Exception();
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $return);
}
i receiver php error undefined variable return
Any effort is highly appreciated
return is a PHP keyword and could lead to confusion.
Are you using PHP 5.x? PHP keywords are allowed since PHP 7.0.0
Try this:
try{
if (!$model->save() {
throw new \Exception(Yii::t('app/job', 'JOB_NOT_FOUND'));
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $e->getMessage());
}

Renci.SshNet : "server response does not contain ssh protocol identification"

I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client. When the user tries to connect to download some files from the SFTP server he gets the message shown below:
Server response does not contain ssh protocol identification
It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop. The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem. I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
{
try
{
SftpClient SFTP;
if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
{
SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
}
else
{
SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
}
SFTP.Connect();
DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + #"\PLOG");
ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
Directory.Delete(Directory.GetCurrentDirectory() + #"\PLOG", true);
SFTP.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Getting PLOGS");
}
}
void DownloadDirectory(SftpClient Client, string Source, string Destination)
{
var Files = Client.ListDirectory(Source);
foreach (var File in Files)
{
if (!File.IsDirectory && !File.IsSymbolicLink)
{
DownloadFile(Client, File, Destination);
}
else if (File.IsSymbolicLink)
{
//Ignore
}
else if (File.Name != "." && File.Name != "..")
{
var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
DownloadDirectory(Client, File.FullName, Dir.FullName);
}
}
}
void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
{
using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
{
Client.DownloadFile(File.FullName, FileStream);
}
}
Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
{
myClient = new SshClient(Host, Port, Username, Password);
myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
myClient.HostKeyReceived += myClient_HostKeyReceived;
myClient.ErrorOccurred += myClient_ErrorOccurred;
}
void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
}
void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
{
e.CanTrust = true;
}
public async void Connect()
{
Task T = new Task(() =>
{
try
{
myClient.Connect();
}
catch (System.Net.Sockets.SocketException)
{
MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
MessageBox.Show(ex.Message, "SSH Authentication Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
MessageBox.Show(ex.GetType().ToString());
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
});
T.Start();
await T;
if (T.IsCompleted)
{
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
}
public void Disconnect()
{
try
{
myClient.Disconnect();
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
public void SendData(string Data)
{
try
{
if (Data.EndsWith("\r\n"))
{
RunCommandAsync(Data, SshCommandRx);
}
else
{
RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
}
//SshCommand Command = myClient.RunCommand(Data);
//OnDataReceived(this, new DataEventArgs(Command.Result));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
private async void RunCommandAsync(String Data, SshCommandCallback Callback)
{
Task<SshCommand> T = new Task<SshCommand>(() =>
{
try
{
SshCommand Command = myClient.RunCommand(Data);
return Command;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
return null;
}
});
T.Start();
await T;
if (T.IsCompleted)
{
Callback(this, T.Result);
}
}
private void SshCommandRx(SshConnection C, SshCommand Command)
{
if (Command != null)
{
string Rx = Command.Result;
//if (Rx.StartsWith(Command.CommandText))
//{
// Rx = Rx.Remove(0, Command.CommandText.Length);
//}
while (Rx.EndsWith("\r\n\r\n") == false)
{
Rx += "\r\n";
}
OnDataReceived(this, new DataEventArgs(Rx));
}
}
I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.

Passing java.security.auth.login.config to Mobilefirst Patform Server

How can we pass following parameter to Mobilefirst Development Server?
-Djava.security.auth.login.config=login.config
I have tried adding it to jvm.options file, and it seems it is passed as parameter without effect.
Following is the code I am trying to execute, and sample of login.config file.
Java code to execute in login module or adapter.
LoginContext context = new LoginContext("SampleClient", new CallbackHandler() {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
NameCallback callBack = (NameCallback) callbacks[0];
callBack.setName("EXAMPLE.COM");
}
});
login.config
SampleClient {
com.sun.security.auth.module.Krb5LoginModule required
default_realm=EXAMPLE.COM;
};
Adding following code before login worked.
try {
Configuration config = Configuration.getConfiguration();
config.getAppConfigurationEntry("SampleClient");
URIParameter uriParameter = new URIParameter(new java.net.URI("file:///path_to_your_file/login.conf"));
Configuration instance = Configuration.getInstance("JavaLoginConfig", uriParameter);
Configuration.setConfiguration(instance);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

Fatal error: Class 'S3Client' not found

I am trying to get all objects from an S3 bucket, but while creating the client by using the factory method, I received an error:
Fatal error: Class 'S3Client' not found in C:\wamp\www\sss.php on line 6
I used the following code:
require 'vendor/autoload.php';
try {
$client = S3Client::factory($credentials);
$arr[] = $client->listObjects(array(
'Bucket'=>'MyglobalBucket1'
));
if ($arr != null) {
var_dump($arr);
}
else {
echo "failed";
}
}
catch(Exception $e) {
echo $e->getMessage();
}
You forgot to use the proper namespace.
use Aws\S3\S3Client;