Sure! Here's an example of how to develop a subscription system using ThinkPHP and Redis.
First, make sure you have ThinkPHP and Redis installed and configured in your project.
- Configure Redis connection in
config/database.php
:
'redis' => [
'type' => 'redis',
'hostname' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
],
- Create a new controller, e.g.,
SubscriptionController.php
:
namespace app\controller;
use think\facade\Redis;
class SubscriptionController
{
public function subscribe()
{
$redis = Redis::connection('redis');
// Subscribe to a channel
$redis->psubscribe(['channel:*'], function ($redis, $pattern, $channel, $message) {
// Handle the received message
echo "Received message: $message\n";
});
}
public function publish()
{
$redis = Redis::connection('redis');
// Publish a message to a channel
$redis->publish('channel:1', 'Hello, world!');
}
}
- Create a route in
route/route.php
to access the subscription controller:
use think\facade\Route;
Route::get('subscription/subscribe', 'SubscriptionController@subscribe');
Route::get('subscription/publish', 'SubscriptionController@publish');
Now you can access the subscribe
action to start listening for messages and the publish
action to send messages to the subscribed channels.
To test it, open two terminal windows and run the following commands:
Terminal 1:
php think run subscription/subscribe
Terminal 2:
php think run subscription/publish
You should see the message "Received message: Hello, world!" in Terminal 1.
That's it! You now have a basic subscription system using ThinkPHP and Redis. You can modify and expand upon this example to suit your specific needs.