thinkphp6 分布式 api环境集成 token验证 + redis + mysql + redis
目录
集成JWT-AUTH(token 相关)
- 基础环境搭建
下载安装 phpstudy 链接 : https://www.xp.cn
- 安装redis
- 安装php redis 支持
安装thinkPhp6
- 官网地址http://www.thinkphp.cn/
- 文档https://www.kancloud.cn/manual/thinkphp6_0/1037481
- 根据文档完成Composer 和 thinkphp的安装
- 安装完成的目录如下
集成JWT-AUTH
- 码云地址https://gitee.com/thans/jwt-auth
- 在项目根目录下执行
-
1.composer require thans/tp-jwt-auth 2.php think jwt:create
用phpstudy搭建网站服务
设置伪静态:
location / {
index index.html index.htm index.php;
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
break;
}
#autoindex on;
}
浏览器访问对应地址 http://localhost:8080/
如果一起顺利可以得到如下效果:
- 如需开启多应用模式参考:http://www.thinkphp.cn/topic/68451.html
- 相关命令:
1.首先刪除app目录下所有其他文件
2.安装多应用模式扩展: composer require topthink/think-multi-app
3.创建三大应用index(前端),admin(后台),common(公共应用)
命令:php think build app
nginx 实现分布式负载均衡
在8088、8089两个端口开两个服务,模拟两台服务器
然后nginx配置:
upstream app_http {
server localhost:8088 weight=1;
server localhost:8089 weight=1;
}
server {
listen 80;
location / {
if (!-e $request_filename){
proxy_pass http://app_http;
}
}
}
thinkphp6配置允许跨域
//AllowCrossDomain
<?php
namespace app\middleware;
class AllowCrossDomain
{
/**
* 设置跨域
* @param $request
* @param \Closure $next
* @return mixed|void
*/
public function handle($request, \Closure $next)
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 1800');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
if (strtoupper($request->method()) == "OPTIONS") {
return Response::create()->send();
}
return $next($request);
}
}
//middleware.php
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
\app\middleware\AllowCrossDomain::class
];