With the expansion of business scale, the amount of data that the database needs to process is also increasing, causing a single database to face pressure. At this time, we need to perform database level sub-database operations to disperse the data into different databases, thereby improving the performance and scalability of the system. This article will introduce how to perform database horizontal sharding operations in ThinkPHP6.
1. What is database horizontal sub-database?
Database horizontal sharding is the process of dispersing data in one database into multiple databases. We can divide the data into different databases according to certain rules (such as according to user ID or time period), thereby reducing the load pressure on a single database. At the same time, when the amount of data is large, horizontal sharding can also improve query efficiency and enhance data security.
2. Implementation of horizontal sub-library in ThinkPHP6
In ThinkPHP6, we can implement horizontal sub-library by using database middleware. Place the database middleware in the MySQL connection of ThinkPHP6 to control the sub-database.
- Install Thinkswoole
In ThinkPHP6, Thinkswoole is used as the database middleware. We need to install Thinkswoole in the project.
Add the ThinkSwoole version information to the composer.json file, and then use composer to install it.
- Modify the database configuration
First find the config/database.php file and replace the MySQL connection with the Swoole connection. Comment out the original MySQL connection information:
// 'mysql' => [ // // 默认数据连接标识 // 'default' => env('database.driver', 'mysql'), // // 数据库连接信息 // 'connections' => [ // 'mysql' => [ // // 数据库类型 // 'type' => 'mysql', // // 主机地址 // 'host' => env('database.hostname', '127.0.0.1'), // // 数据库名 // 'database' => env('database.database', ''), // // 用户名 // 'username' => env('database.username', 'root'), // // 密码 // 'password' => env('database.password', ''), // // 端口 // 'hostport' => env('database.hostport', '3306'), // // 数据库连接参数 // 'params' => [], // // 数据库编码默认采用utf8 // 'charset' => 'utf8', // // 数据库表前缀 // 'prefix' => env('database.prefix', ''), // // 数据库调试模式 // 'debug' => env('database.debug', true), // // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) // 'deploy' => 0, // // 数据库读写是否分离 主从式有效 // 'rw_separate' => false, // // 读写分离后 主服务器数量 // 'master_num' => 1, // // 指定从服务器序号 // 'slave_no' => '', // // 是否严格检查字段是否存在 // 'fields_strict' => true, // // 数据集返回类型 // 'resultset_type' => 'array', // // 自动写入时间戳字段 // 'auto_timestamp' => false, // // 时间字段取出后的默认时间格式 // 'datetime_format' => false, // // Builder类 // 'builder' => '', // // Query类 // 'query' => '\think\db\Query', // // 是否需要进行SQL性能分析 // 'sql_explain' => false, // ], // ], // ],
Add Swoole connection information:
// swoole 'swoole' => [ // 默认数据连接标识 'default' => 'swoole', // 数据库连接信息 'connections' => [ 'swoole' => [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => [ '127.0.0.1:3305', '127.0.0.1:3306', ], // 数据库名 'database' => 'test', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8mb4 'charset' => 'utf8mb4', // 数据库表前缀 'prefix' => '', // 数据库调试模式 'debug' => true, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0, // 数据库读写是否分离 主从式有效 'rw_separate' => false, // 读写分离后 主服务器数量 'master_num' => 1, // 指定从服务器序号 'slave_no' => '', // 自动写入时间戳字段 'auto_timestamp' => false, // 时间字段取出后的默认时间格式 'datetime_format' => 'Y-m-d H:i:s', // Builder类 'builder' => '', // Query类 'query' => '\think\db\Query', // 是否需要进行SQL性能分析 'sql_explain' => false, ], ], ],
In the above code, we defined two server addresses (127.0.0.1:3305 and 127.0.0.1:3306 ), this is to implement sub-library of multiple data nodes. Database name, user name, password and other information remain unchanged.
- Create database middleware
Create the database middleware of Db.php in the app/middleware directory and add the following code:
<?php namespace appmiddleware; use thinkRequest; use thinkContainer; class Db { public function handle(Request $request, Closure $next) { $serverIds = $this->getServerIds($request); //定义一个连接池 $conns = []; foreach($serverIds as $sid) { $sid = $request->$sid; if(empty($conns[$sid])) { $conns[$sid] = Container::getInstance() ->make('db')->connect($sid); } } Container::getInstance()->bind('db', function() use ($conns) { return $conns; }); return $next($request); } protected function getServerIds(Request $request) { return ['uid']; } }
Create here A middleware called Db is created. In the handle method, first obtain the server ID array of the current request. Then compare these server addresses with the existing addresses in the connection pool $cons. If they do not exist, add them to the connection pool. Finally, bind the connection pool $conns to the container instance. In the getServerIds method, we can set the name of the server ID, which defaults to uid.
- Register middleware
Add the following code to config/middleware.php:
return [ ... appmiddlewareDb::class, ];
This code is used to register middleware. Added our Db middleware to the list of middleware execution activities.
- Implement the sub-library operation
Next, we will implement the horizontal sub-library operation in the model. Taking the user table as an example, the user ID is divided into 100,000 and 100,000 as the limit of a database, which means that data with user IDs between 0 and 100,000 are stored in a database, and so on, until the user ID is in Data between 900,000 and 1 million is stored in the 10th database.
<?php namespace appmodel; use thinkModel; class User extends Model { protected $connection = [ 1 => 'user_1', 2 => 'user_2', 3 => 'user_3', 4 => 'user_4', 5 => 'user_5', 6 => 'user_6', 7 => 'user_7', 8 => 'user_8', 9 => 'user_9', 10 => 'user_10', ]; protected $pk = 'uid'; public function getTableName(): string { $id = ceil($this->id / 100000); return $this->connection[$id] . '.' . $this->table; } }
Here we define 10 database connections, each connection represents a database shard, achieving the purpose of horizontal sharding. Then we define the getTableName method to obtain the data table name corresponding to the current model. Calculate the database connection that needs to be accessed based on the primary key ID value in the model, and return the combination of database connection and data table name.
Summary:
This article introduces the horizontal sub-library operation in ThinkPHP6. As business continues to expand and data scale increases, horizontal sharding can improve system performance and scalability, as well as enhance data security. In ThinkPHP6, you can use Thinkswoole middleware and other methods to implement horizontal sub-library operations.
The above is the detailed content of How to perform database horizontal sub-database operation in ThinkPHP6?. For more information, please follow other related articles on the PHP Chinese website!

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了关于使用think-queue来实现普通队列和延迟队列的相关内容,think-queue是thinkphp官方提供的一个消息队列服务,下面一起来看一下,希望对大家有帮助。

thinkphp基于的mvc分别是指:1、m是model的缩写,表示模型,用于数据处理;2、v是view的缩写,表示视图,由View类和模板文件组成;3、c是controller的缩写,表示控制器,用于逻辑处理。mvc设计模式是一种编程思想,是一种将应用程序的逻辑层和表现层进行分离的方法。

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了使用jwt认证的问题,下面一起来看一下,希望对大家有帮助。

thinkphp查询库是否存在的方法:1、打开相应的tp文件;2、通过“ $isTable=db()->query('SHOW TABLES LIKE '."'".$data['table_name']."'");if($isTable){...}else{...}”方式验证表是否存在即可。

thinkphp扩展有:1、think-migration,是一种数据库迁移工具;2、think-orm,是一种ORM类库扩展;3、think-oracle,是一种Oracle驱动扩展;4、think-mongo,一种MongoDb扩展;5、think-soar,一种SQL语句优化扩展;6、porter,一种数据库管理工具;7、tp-jwt-auth,一个jwt身份验证扩展包。

本篇文章给大家带来了关于ThinkPHP的相关知识,其中主要整理了使用think-queue实现redis消息队列的相关问题,下面一起来看一下,希望对大家有帮助。

在thinkphp3.2中,可以利用define关闭调试模式,该标签用于变量和常量的定义,将入口文件中定义调试模式设为FALSE即可,语法为“define('APP_DEBUG', false);”;开启调试模式将参数值设置为true即可。


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
