PHP Implementation Load Balancing session Sharing redis Cache Operation Example
- 2021-11-01 02:42:12
- OfStack
This article illustrates the PHP implementation of load balancing session sharing redis cache operations. Share it for your reference, as follows:
1. Create the html form page first
<meta chatset='utf-8'>
<center>
<form action="se.php" method="post">
<table>
<tr>
<td> Account number: </td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td> Password: </td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value=" Login "></td>
</tr>
</table>
</form>
</center>
2. Create a file that accepts the form
<?php
header('content-type:text/html;charset=utf-8');
set_time_limit(10);
ini_set("session.save_handler",'redis');// Open php.ini In redis Configure
ini_set("session.save_path","tcp://192.168.1.70:6379");// No. 1 1 Of a server redis
session_start();// Open session
$username = $_POST['username'];
$_SESSION['username'] = $username;
echo "<script>alert(' Login successful! ');location.href='from.php'</script>";// After successful login, jump to the welcome login page
?>
3. Jump to from. php to determine whether session in redis of the first server is stored in session of this server
<?php
header('content-type:text/html;charset=utf-8');
set_time_limit(10);
ini_set("session.save_handler",'redis');// Open php.ini In redis Configure
ini_set("session.save_path","tcp://192.168.1.70:6379");// No. 1 1 Of a server redis
session_start();// Open session
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';// Determine whether there is a current existence session
//$id = $_SESSION['PHPSESSID'];
//echo $id;
if(empty($username)){
echo "<script>alert(' Please log in again! ');location.href='index.php'</script>";
}else{
echo " Welcome ".$username." Login ";
}
?>
This is a simple implementation of redis session sharing function, to test the need for two servers, it is recommended to use linux better
For installing redis on linux, please refer to "Method for Installing redis and redis Extensions on Linux Platform"
For more readers interested in PHP related content, please check the topics on this site: "Summary of php Cache Technology", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Summary of PHP Error and Exception Handling Methods", "Introduction to php Object-Oriented Programming", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.