Redis 缓存

Redis 缓存使用 Predis 做为依赖,还需要安装 kain/think-redis

  1. composer require kain/think-redis

安装后服务将自动注册,然后需要更新配置 config/database.php,例如:

  1. return [
  2. 'redis' => [
  3. 'default' => [
  4. // 服务器地址
  5. 'host' => Env::get('redis.host', '127.0.0.1'),
  6. // 密码
  7. 'password' => Env::get('redis.password', null),
  8. // 端口
  9. 'port' => Env::get('redis.port', 6379),
  10. // 数据库号
  11. 'database' => Env::get('redis.db', 0),
  12. ]
  13. ],
  14. ];
  • scheme string 连接协议,支持 tcp unix http
  • host string 目标服务器的IP或主机名
  • port int 目标服务器的TCP / IP端口
  • path string 使用 unix socket 的文件路径
  • database int 逻辑数据库
  • password string 身份验证口令
  • async boolean 指定是否以非阻塞方式建立与服务器的连接
  • persistent boolean 指定在脚本结束其生命周期时是否应保持基础连接资源处于打开状态
  • timeout float 用于连接到Redis服务器的超时
  • read_write_timeout float 在对基础网络资源执行读取或写入操作时使用的超时
  • alias string 通过别名来标识连接
  • weight integer 集群权重
  • iterable_multibulk boolean 当设置为true时,Predis将从Redis返回multibulk作为迭代器实例而不是简单的PHP数组
  • throw_errors boolean 设置为true时,Redis生成的服务器错误将转换为PHP异常

测试写入一个缓存

  • client(string $name = ‘default’)
    • name string 配置标识
    • return Predis\Client
  1. use think\support\facade\Redis;
  2. Redis::client()->set('name', 'abc')

使用 pipeline 批量执行一万条写入

  1. use think\support\facade\Redis;
  2. Redis::client()->pipeline(function (Pipeline $pipeline) {
  3. for ($i = 0; $i < 10000; $i++) {
  4. $pipeline->set('test:' . $i, $i);
  5. }
  6. });

面向缓存使用事务处理

  1. use think\support\facade\Redis;
  2. // success
  3. Redis::client()->transaction(function (MultiExec $multiExec) {
  4. $multiExec->set('name:a', 'a');
  5. $multiExec->set('name:b', 'b');
  6. });
  7. // failed
  8. Redis::client()->transaction(function (MultiExec $multiExec) {
  9. $multiExec->set('name:a', 'a');
  10. // mock exception
  11. throw new Exception('error');
  12. $multiExec->set('name:b', 'b');
  13. });

AMQP 消息队列

AMQP 消息队列操作类使用 kain/simplify-amqp 做为依赖,首先使用 composer 安装操作服务

  1. composer require kain/think-amqp

安装后服务将自动注册,然后需要更新配置 config/queue.php,例如:

  1. return [
  2. 'rabbitmq' => [
  3. 'default' => [
  4. // 服务器地址
  5. 'hostname' => Env::get('rabbitmq.host', 'localhost'),
  6. // 端口号
  7. 'port' => Env::get('rabbitmq.port', 5672),
  8. // 虚拟域
  9. 'virualhost' => Env::get('rabbitmq.virualhost', '/'),
  10. // 用户名
  11. 'username' => Env::get('rabbitmq.username', 'guest'),
  12. // 密码
  13. 'password' => Env::get('rabbitmq.password', 'guest'),
  14. ]
  15. ]
  16. ];

AMQP 客户端

  • client(string $name = ‘default’)
    • name string 配置标识
    • return simplify\amqp\AMQPClient

创建默认信道

  • channel(Closure $closure, string $name = ‘default’, array $options = [])
    • closure Closure 信道处理
    • name string 配置标识
    • options array 操作配置
      • transaction boolean 开启事务,默认 false
      • channel_id string 定义信道ID,默认 null
      • reply_code int 回复码,默认 0
      • reply_text string 回复文本,默认 ''
      • method_sig array 默认 [0,0]
  1. use think\support\facade\AMQP;
  2. use simplify\amqp\AMQPManager;
  3. AMQP::channel(function (AMQPManager $manager) {
  4. // Declare
  5. $manager->queue('test')
  6. ->setDeclare([
  7. 'durable' => true
  8. ]);
  9. // Or delete
  10. $manager->queue('test')
  11. ->delete();
  12. });

创建包含事务的信道

  • channeltx(Closure $closure, string $name = ‘default’, array $options = [])
  1. use think\support\facade\AMQP;
  2. use simplify\amqp\AMQPManager;
  3. AMQP::channeltx(function (AMQPManager $manager) {
  4. $manager->publish(
  5. AMQPManager::message(
  6. json_encode([
  7. "name" => "test"
  8. ])
  9. ),
  10. '',
  11. 'test'
  12. );
  13. // 当返回为 false 时,将不提交发布消息
  14. return true;
  15. });

关于 simplify\amqp\AMQPManager 对象完整使用可查看 simplify-amqp 的单元测试 tests 目录

ElasticSearch 全文搜索

ElasticSearch 可对数据进行全文搜索或针对数据分析查询,首先使用 composer 安装操作服务

  1. composer require kain/think-elastic

安装后服务将自动注册,然后需要更新配置 config/database.php

  1. return [
  2. 'elasticsearch' => [
  3. 'default' => [
  4. // 集群连接
  5. 'hosts' => explode(',', Env::get('elasticsearch.hosts', 'localhost:9200')),
  6. // 重试次数
  7. 'retries' => 0,
  8. // 公共CA证书
  9. 'SSLVerification' => null,
  10. // 开启日志
  11. 'logger' => null,
  12. // 配置 HTTP Handler
  13. 'handler' => null,
  14. // 设置连接池
  15. 'connectionPool' => Elasticsearch\ConnectionPool\StaticNoPingConnectionPool::class,
  16. // 设置选择器
  17. 'selector' => Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector::class,
  18. // 设置序列化器
  19. 'serializer' => Elasticsearch\Serializers\SmartSerializer::class
  20. ]
  21. ]
  22. ];
  • hosts array 集群连接
  • retries int 重试次数
  • SSLVerification string 公共CA证书
  • logger LoggerInterface 开启日志
  • handler mixed 配置 HTTP Handler
  • connectionPool AbstractConnectionPool|string 设置连接池
  • selector SelectorInterface|string 设置选择器
  • serializer SerializerInterface|string 设置序列化器

客户端

  • client(string $label = ‘default’)
    • label string 配置label
    • return Elasticsearch\Client
  1. use think\support\facade\ES;
  2. $response = ES::client()->index([
  3. 'index' => 'test',
  4. 'id' => 'test',
  5. 'body' => [
  6. 'value' => 1
  7. ]
  8. ]);
  9. // ^ array:8 [▼
  10. // "_index" => "test"
  11. // "_type" => "_doc"
  12. // "_id" => "test"
  13. // "_version" => 1
  14. // "result" => "created"
  15. // "_shards" => array:3 [▼
  16. // "total" => 2
  17. // "successful" => 1
  18. // "failed" => 0
  19. // ]
  20. // "_seq_no" => 0
  21. // "_primary_term" => 1
  22. // ]

获取文档

  1. use think\support\facade\ES;
  2. $response = ES::client()->get([
  3. 'index' => 'test',
  4. 'id' => 'test'
  5. ]);
  6. // ^ array:8 [▼
  7. // "_index" => "test"
  8. // "_type" => "_doc"
  9. // "_id" => "test"
  10. // "_version" => 1
  11. // "_seq_no" => 0
  12. // "_primary_term" => 1
  13. // "found" => true
  14. // "_source" => array:1 [▼
  15. // "value" => 1
  16. // ]
  17. // ]

搜索文档

  1. use think\support\facade\ES;
  2. $response = ES::client()->search([
  3. 'index' => 'test',
  4. 'body' => [
  5. 'query' => [
  6. 'match' => [
  7. 'value' => 1
  8. ]
  9. ]
  10. ]
  11. ]);
  12. // ^ array:4 [▼
  13. // "took" => 4
  14. // "timed_out" => false
  15. // "_shards" => array:4 [▼
  16. // "total" => 1
  17. // "successful" => 1
  18. // "skipped" => 0
  19. // "failed" => 0
  20. // ]
  21. // "hits" => array:3 [▼
  22. // "total" => array:2 [▼
  23. // "value" => 1
  24. // "relation" => "eq"
  25. // ]
  26. // "max_score" => 1.0
  27. // "hits" => array:1 [▼
  28. // 0 => array:5 [▼
  29. // "_index" => "test"
  30. // "_type" => "_doc"
  31. // "_id" => "test"
  32. // "_score" => 1.0
  33. // "_source" => array:1 [▼
  34. // "value" => 1
  35. // ]
  36. // ]
  37. // ]
  38. // ]
  39. // ]

删除文档

  1. use think\support\facade\ES;
  2. $response = ES::client()->delete([
  3. 'index' => 'test',
  4. 'id' => 'test'
  5. ]);
  6. // ^ array:8 [▼
  7. // "_index" => "test"
  8. // "_type" => "_doc"
  9. // "_id" => "test"
  10. // "_version" => 2
  11. // "result" => "deleted"
  12. // "_shards" => array:3 [▼
  13. // "total" => 2
  14. // "successful" => 1
  15. // "failed" => 0
  16. // ]
  17. // "_seq_no" => 1
  18. // "_primary_term" => 1
  19. // ]

删除索引

  1. use think\support\facade\ES;
  2. $response = ES::client()->indices()->delete([
  3. 'index' => 'test',
  4. ]);
  5. // ^ array:1 [▼
  6. // "acknowledged" => true
  7. // ]

创建索引

  1. use think\support\facade\ES;
  2. $response = ES::client()->indices()->create([
  3. 'index' => 'test'
  4. ]);
  5. // ^ array:3 [▼
  6. // "acknowledged" => true
  7. // "shards_acknowledged" => true
  8. // "index" => "test"
  9. // ]

think-elastic 使用了 elasticsearch/elasticsearch ,更多方法可查看 Elasticsearch-PHP 完整文档

阿里云相关扩展

阿里云相关扩展是针对阿里云库的统一简化,首先使用 composer 安装操作服务

  1. composer require kain/think-aliyun-extra

安装后服务将自动注册,然后需要更新配置 config/aliyun.php,例如:

  1. return [
  2. 'accessKeyId' => env('aliyun.id'),
  3. 'accessKeySecret' => env('aliyun.secret'),
  4. 'oss' => [
  5. 'endpoint' => env('aliyun.oss_endpoint'),
  6. 'extranet' => env('aliyun.oss_extranet'),
  7. 'bucket' => env('aliyun.oss_bucket')
  8. ]
  9. ];
  • accessKeyId string 阿里云 keyid
  • accessKeySecret string 阿里云 key secret
  • oss
    • endpoint string 对象存储endpoint
    • extranet string 对象存储外网地址
    • bucket string 桶名

获取对象存储客户端

  • Oss::getClient(bool $extranet = false): OssClient

上传至阿里云对象存储

  • Oss::put(string $name): string
    • name string File 请求文件
    • return string 对象名称
  1. use think\support\facade\Oss;
  2. public function uploads()
  3. {
  4. try {
  5. $saveName = Oss::put('image');
  6. return [
  7. 'error' => 0,
  8. 'data' => [
  9. 'savename' => $saveName,
  10. ]
  11. ];
  12. } catch (\Exception $e) {
  13. return [
  14. 'error' => 1,
  15. 'msg' => $e->getMessage()
  16. ];
  17. }
  18. }

华为云相关扩展

华为云相关扩展是针对华为云库的统一简化,首先使用 composer 安装操作服务

  1. composer require kain/think-huaweicloud-extra

安装后服务将自动注册,然后需要更新配置 config/huaweicloud.php,例如:

  1. return [
  2. 'accessKeyId' => env('huaweicloud.id'),
  3. 'accessKeySecret' => env('huaweicloud.secret'),
  4. 'obs' => [
  5. 'endpoint' => env('huaweicloud.obs_endpoint'),
  6. 'bucket' => env('huaweicloud.obs_bucket')
  7. ]
  8. ];
  • accessKeyId string 华为云 keyid
  • accessKeySecret string 华为云 key secret
  • obs
    • endpoint string 对象存储endpoint
    • bucket string 桶名

获取对象存储客户端

  • Obs::getClient(): ObsClient

上传至华为云对象存储

  • Obs::put(string $name): string
    • name string File 请求文件
    • return string 对象名称
  1. use think\support\facade\Obs;
  2. public function uploads()
  3. {
  4. try {
  5. $saveName = Obs::put('image');
  6. return [
  7. 'error' => 0,
  8. 'data' => [
  9. 'savename' => $saveName,
  10. ]
  11. ];
  12. } catch (\Exception $e) {
  13. return [
  14. 'error' => 1,
  15. 'msg' => $e->getMessage()
  16. ];
  17. }
  18. }