


PHP's Laravel framework combines the use and deployment of MySQL and Redis database, laravelredis_PHP tutorial
PHP's Laravel framework is combined with MySQL and Redis database usage and deployment, laravelredis
Rather than familiarizing yourself with official documents, it is more important to set up the framework environment.
Zero, environment introduction
- Operating system: centOS
- Database: mysql 5.6 (Alibaba Cloud RDS)
- PHP 5.4.4 (>=5.4 is enough)
- Laravel 5.0
1. Install LNMP
Before installing Laravel, you need to set up the Linux Nginx Mysql Php environment. The specific construction steps will not be detailed here.
P.S.
- Linux Alibaba Cloud already comes with it. This article uses centOS 6.5 64-bit ECS
- Regarding the choice between Nginx and Apache, it depends on your own preferences. This article uses the reverse proxy expert Nginx
- Whether to install Mysql depends on your own situation. For example, if you use Alibaba Cloud's RDS, then there is no need to install it
2. Install Composer
Composer is a tool used to manage PHP package dependencies. Laravel is using this tool for dependency management. There are two installation methods
Partial installation
Global installation means it can be used in any directory of the system. This article only introduces this installation method. Official installation documentation
Execute the following two commands respectively
curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer
The installation is complete, use the following command to check whether the installation is successful
composer -V
The version number appears, which means the installation is successful
3. Install Laravel
Just follow Laravel’s official documentation. It is recommended to use [installation tool through Laravel]. There are no pitfalls. Skip it here
Tip: Since Laravel also depends on some PHP extensions, use yum to install
sudo install yum php-mysql php-mcrypt php-mbstring php-tokenizer php-openssl
After the installation is complete, add the following configuration at the bottom of the Nginx configuration file (usually /etc/nginx/conf.d/default.conf)
location / { try_files $uri $uri/ /index.php?$query_string; }
Go to your laravel project directory and see the storage and vendor folders. Use the following commands to modify its file read and write permissions so that Nginx users can read and write it
sudo chmod -R 766 storage sudo chmod -R 766 vendor
4. Let MVC run!
Before this, you should read the official documentation on routing, controllers, database usage basics, Eloquent ORM
At this point, you can start coding and develop an MVC demo. The function of this demo is to read the database table tbl_item from the database and respond to the browser in json format.
Assume that you have initialized your web app through laravel new demo.
- Create a database (demo) and a table (tbl_item) in the database (fields can be determined as desired)
- Configuration configuration file config/database.php
- Directly operate the database and insert a piece of data into tbl_item
- Start coding
Add the following code at the bottom of demo/app/http/routes.php:
Route::get('/item/{id}', 'ItemController@showItem');
Add a new file ItemController.php to the demo/app/http/controllers/ directory, the code is as follows:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Item as Item; class ItemController extends Controller { private $model; public function __construct() { $this->model = new Item(); } public function showItem($id) { $users = $this->model->fetchAll(); echo json_encode($users); Log::info('获取用户列表,通过msyql'); } }
The new file Item.php in the demo/app/ directory has the following code
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Item extends Model { protected $fillable = ['name', 'price']; protected $guarded = ['id']; /** * The database table used by the model. * default: tbl_items * @var string */ // protected $table = 'tbl_items'; public function fetchAll(){ $items = $this->all()->toJson(); return $items; } }
Use a browser to access http://yourIp/item/1 to list all item data
5. Laravel combined with Redis
Direct connection to DB is not enough, database access will soon become the bottleneck of the system. We introduce caching Redis. Still the same idea, let the system run first.
1. Install and start Redis
Installation
$ wget http://download.redis.io/releases/redis-3.0.1.tar.gz $ tar xzf redis-3.0.1.tar.gz $ cd redis-3.0.1 $ make
Start
$ src/redis-server
View the official download and installation documentation, just a few commands are needed
2. Install PHP PRedis
PRedis is an extension package for PHP to access redis. You only need to download the original code and there is no need to install PHP extensions (such as php-redis.so). But before that, we need to introduce a composer, because laravel uses it to install third-party packages (manage dependencies).
cd to the path of your App, modify composer.json, add "predis/predis":"~1.0.1" in the require field, then sudo composer update in the current directory, and the package will be automatically downloaded. Required extension packages, these extension packages will be placed in the vendor directory. If there are errors such as insufficient memory, it seems that the reason is insufficient memory allocation. Just restart the server. The complete solution is to modify the server configuration, but I don’t know where to change it. I will add it later
To configure related configurations, just check the official documentation. Mainly configure config/database.php
'redis' => array( 'cluster' => false, 'default' => array('host' => '127.0.0.1', 'port' => 6379) )
3. coding
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User as User; use Illuminate\Support\Facades\Redis as Redis; class UserController extends Controller { // use User; private $model; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->model = new User(); } /** * Show * * @return Response */ public function showUser($id) { $redis = Redis::connection('default'); $cacheUsers = $redis->get('userList'); if( $cacheUsers ){ $users = $cacheUsers; print_r($users); Log::info('获取用户列表,通过redis'); }else{ $users = $this->model->fetchAll(); $redis->set('userList', $users); print_r($users); Log::info('获取用户列表,通过msyql'); } } }
Articles you may be interested in:
- Python uses Redis to implement a job scheduling system (super simple)
- php method of processing sessions based on redis
- redis Performance issues of the hGetAll function (remember the annoying HGETALL of Redis)
- Installation and deployment of Redis under Linux
- Java connection to redis in Vmware
- Nginx configuration srcache_nginx module Establishing a cache system with Redis
- Tutorial on installing and configuring Redis database under CenOS system
- C Access Redis’s mset binary data interface packaging solution
- C Developed Redis data import Tool optimization
- A brief discussion on the coordinated use of Redis in distributed systems

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

UseGuzzleforrobustHTTPrequestswithheadersandtimeouts.2.ParseHTMLefficientlywithSymfonyDomCrawlerusingCSSselectors.3.HandleJavaScript-heavysitesbyintegratingPuppeteerviaPHPexec()torenderpages.4.Respectrobots.txt,adddelays,rotateuseragents,anduseproxie

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.
