流量分发优化

This commit is contained in:
wong
2025-07-14 18:16:36 +08:00
parent e0583db19a
commit 9736416fff
5 changed files with 149 additions and 8 deletions

View File

@@ -7,6 +7,7 @@ use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\facade\Cache;
use think\facade\Log;
use think\Queue;
@@ -25,6 +26,90 @@ class SwitchFriendsCommand extends Command
protected function execute(Input $input, Output $output)
{
//处理流量分过期数据
$expUserData = Db::name('workbench_traffic_config_item')
->where('expTime','<=',time())
->where('isRecycle',0)
->select();
// 根据accountId对数组进行归类
$groupedByAccount = [];
foreach ($expUserData as $friend) {
$accountId = $friend['wechatAccountId'];
if (!isset($groupedByAccount[$accountId])) {
$groupedByAccount[$accountId] = [];
}
$friendId = $friend['wechatFriendId'];
$groupedByAccount[$accountId][] = $friendId;
}
// 对每个账号的好友进行20个为一组的分组
foreach ($groupedByAccount as $accountId => $accountFriends) {
//检索主账号
$account = Db::name('users')->where('s2_accountId',$accountId)->find();
if (empty($account)) {
continue;
}
$account2 = Db::name('users')
->where('s2_accountId','>',0)
->where('companyId',$account['companyId'])
->order('s2_accountId ASC')
->find();
if (empty($account2)) {
continue;
}
$newaAccountId = $account2['s2_accountId'];
$chunks = array_chunk($accountFriends, 20);
$output->writeln('账号 ' . $newaAccountId . ' 共有 ' . count($accountFriends) . ' 个好友,分为 ' . count($chunks) . ' 组');
$automaticAssign = new AutomaticAssign();
foreach ($chunks as $chunkIndex => $chunk) {
$output->writeln('处理账号 ' . $newaAccountId . ' 第 ' . ($chunkIndex + 1) . ' 组,共 ' . count($chunk) . ' 个好友');
try {
$friendIds = implode(',', $chunk);
$res = $automaticAssign->multiAllotFriendToAccount([
'wechatFriendIds' => $friendIds,
'toAccountId' => $newaAccountId,
]);
$res = json_decode($res, true);
if ($res['code'] == 200){
//修改数据库
Db::table('s2_wechat_friend')
->where('id',$friendIds)
->update([
'accountId' => $account2['s2_accountId'],
'accountUserName' => $account2['account'],
'accountRealName' => $account2['username'],
'accountNickname' => $account2['username'],
]);
Db::name('workbench_traffic_config_item')
->whereIn('wechatFriendId',$friendIds)
->where('wechatAccountId',$accountId)
->update([
'isRecycle' => 1,
'recycleTime' => time(),
]);
$output->writeln('✓ 成功切换好友:' . $friendIds . ' 到账号:' . $newaAccountId);
} else {
$output->writeln('✗ 切换失败 - 好友:' . $friendIds . ' 到账号:' . $newaAccountId . ' 结果:' . $res['msg']);
}
} catch (\Exception $e) {
$output->writeln('✗ 切换异常 - 好友:' . implode(',', $chunk) . ' 到账号:' . $newaAccountId . ' 错误:' . $e->getMessage());
}
// 每组处理完后稍作延迟,避免请求过于频繁
if ($chunkIndex < count($chunks) - 1) {
sleep(1);
}
}
}
$cacheKey = 'allotWechatFriend';
$now = time();
$maxRetry = 5;