在FastAdmin进行微信开发时,EasyWechat库默认使用文件缓存来存储微信的access_token。如果你的服务端存在分布式部署,可能会遇到access_token不一致的问题,从而导致以下错误:
{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest rid: "}
为了解决这个问题,我们需要将EasyWechat的缓存机制修改为Redis。以下是实现这一配置的两种方法:
全局配置
在全局配置中,我们可以设置Redis作为EasyWechat的缓存。这样,无论何时初始化EasyWechat应用,都会使用Redis来缓存access_token。
use EasyWeChat\Factory;
use EasyWeChat\Cache\RedisCache;
use EasyWeChat\Events\ApplicationInitialized;
$config = [
'app_id' => 'your_app_id',
'secret' => 'your_secret',
'events' => [
'listen' => [
ApplicationInitialized::class => [
function ($event) {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_redis_password'); // 密码为空时可忽略
$cache = new RedisCache($redis);
$event->app->rebind('cache', $cache);
}
],
],
],
//...
];
// 将`$config`配置放在一个通用的配置文件中
$app = Factory::officialAccount($config);
按需配置
如果你希望按需配置Redis缓存,可以在初始化EasyWechat应用后设置Redis缓存。
use EasyWeChat\Factory;
use EasyWeChat\Cache\RedisCache;
$config = [
'app_id' => 'your_app_id',
'secret' => 'your_secret',
//...
];
$app = Factory::officialAccount($config);
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_redis_password'); // 密码为空时可忽略
$cache = new RedisCache($redis);
$app->rebind('cache', $cache);
缓存优化
为了优化Redis连接,如果你的框架缓存也使用Redis,可以将Redis连接从框架中获取,避免重复连接。
$redis = \think\Cache::store('redis')->handler();
$cache = new RedisCache($redis);
$app->rebind('cache', $cache);