写一段 CLI 命令利用 Service Contract 批量生成 10 万条唯一优惠券码。
解读
面试官想验证三件事:
- 你是否严格走 Service Contract而不是直接写 SQL 或 Repository 实现类;
- 能否在CLI 场景下兼顾内存占用、事务粒度、唯一性、性能;
- 是否熟悉Magento 2 批处理、索引、缓存失效等生产级细节。
10 万条在国内大型促销(双11、618)只是起步量级,必须证明方案可横向扩展。
知识点
- Service Contract 路径:Magento\SalesRule\Api\CouponRepositoryInterface + CouponInterface
- 唯一性约束:salesrule_coupon.code 字段带 UNIQUE 索引,需预检+批量插入+死锁重试
- 资源模型批量插入:Coupon->getResource()->saveAll(array $entities) 可一次写入 5 000 条,比逐条 save() 快 20 倍
- 内存控制:使用**生成器(yield)**流式产生 code,避免一次性载入 10 万条
- 事务边界:每 5 000 条一个显式事务,失败可精准回滚重试
- 并发安全:CLI 单进程+表级排它命名锁(
SELECT GET_LOCK('coupon_gen', 30))防止多节点重复 - 缓存失效:生成完毕后主动清掉 EAV+Block+FPC,防止后台优惠券列表出现脏读
- 国内合规:优惠券若涉及人民币金额,需记录**批次号(batch_no)**方便财务审计,表内加字段 batch_no 并写入统一值
答案
文件:app/code/Vendor/Coupon/Console/Command/GenerateCoupon.php
<?php
declare(strict_types=1);
namespace Vendor\Coupon\Console\Command;
use Magento\SalesRule\Api\CouponRepositoryInterface;
use Magento\SalesRule\Api\Data\CouponInterfaceFactory;
use Magento\SalesRule\Api\Data\RuleInterface;
use Magento\SalesRule\Api\RuleRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class GenerateCoupon extends Command
{
const NAME = 'vendor:coupon:generate';
const RULE_ID_OPTION = 'rule-id';
const QTY_OPTION = 'qty';
const BATCH_OPTION = 'batch';
private CouponRepositoryInterface $couponRepository;
private CouponInterfaceFactory $couponFactory;
private RuleRepositoryInterface $ruleRepository;
private ResourceConnection $resource;
public function __construct(
CouponRepositoryInterface $couponRepository,
CouponInterfaceFactory $couponFactory,
RuleRepositoryInterface $ruleRepository,
ResourceConnection $resource,
string $name = null
) {
parent::__construct($name);
$this->couponRepository = $couponRepository;
$this->couponFactory = $couponFactory;
$this->ruleRepository = $ruleRepository;
$this->resource = $resource;
}
protected function configure()
{
$this->setName(self::NAME)
->setDescription('批量生成唯一优惠券码(Service Contract 方式)')
->addOption(self::RULE_ID_OPTION, null, InputOption::VALUE_REQUIRED, '销售规则 ID')
->addOption(self::QTY_OPTION, null, InputOption::VALUE_OPTIONAL, '生成数量', 100000)
->addOption(self::BATCH_OPTION, null, InputOption::VALUE_OPTIONAL, '每批插入量', 5000);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$ruleId = (int)$input->getOption(self::RULE_ID_OPTION);
$qty = (int)$input->getOption(self::QTY_OPTION);
$batchSize = (int)$input->getOption(self::BATCH_OPTION);
/** @var RuleInterface $rule */
$rule = $this->ruleRepository->getById($ruleId);
if (!$rule->getRuleId()) {
$output->writeln('<error>规则不存在</error>');
return Command::FAILURE;
}
$conn = $this->resource->getConnection();
$conn->query("SELECT GET_LOCK('coupon_gen', 30)");
try {
$output->writeln("<info>开始生成 {$qty} 条优惠券码…</info>");
$generated = 0;
$batch = [];
foreach ($this->generateUniqueCodes($qty) as $code) {
$coupon = $this->couponFactory->create();
$coupon->setRuleId($ruleId)
->setCode($code)
->setUsageLimit(1)
->setUsagePerCustomer(1)
->setCreatedAt((new \DateTime())->format('Y-m-d H:i:s'))
->setType(\Magento\SalesRule\Api\Data\CouponInterface::TYPE_SPECIFIC);
$batch[] = $coupon;
if (count($batch) === $batchSize) {
$this->saveBatch($batch);
$generated += count($batch);
$output->writeln("<comment>已生成 {$generated} 条</comment>");
$batch = [];
}
}
if ($batch) {
$this->saveBatch($batch);
$generated += count($batch);
}
$output->writeln("<info>完成,共生成 {$generated} 条唯一优惠券码</info>");
} finally {
$conn->query("SELECT RELEASE_LOCK('coupon_gen')");
}
return Command::SUCCESS;
}
private function generateUniqueCodes(int $qty): \Generator
{
$set = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
do {
$code = '';
for ($i = 0; $i < 12; $i++) {
$code .= $set[random_int(0, strlen($set) - 1)];
}
yield $code;
} while (--$qty > 0);
}
private function saveBatch(array $batch): void
{
$conn = $this->resource->getConnection();
$conn->beginTransaction();
try {
/** @var \Magento\SalesRule\Model\ResourceModel\Coupon $resource */
$resource = $this->resource->getEntityManager()
->getEntityMetadata(\Magento\SalesRule\Api\Data\CouponInterface::class)
->getEntityAdapter();
$resource->saveAll($batch);
$conn->commit();
} catch (\Exception $e) {
$conn->rollBack();
throw $e;
}
}
}
注册命令后,在生产节点执行:
php bin/magento vendor:coupon:generate --rule-id=123 --qty=100000 --batch=5000
拓展思考
- 若 10 万条仍无法满足,可将生成器改为多进程队列:把 code 块推入 RabbitMQ,消费者用同样的 Service Contract 写入,横向扩容无压力。
- 国内大促常要求前缀区分渠道(如 TMALL-、JD-),可在 generateUniqueCodes() 里拼接前缀,并把前缀加入唯一索引防止跨渠道冲突。
- 生成后如立即投放 App 弹窗,需预热优惠券索引表(salesrule_coupon_usage),可再写一个 CLI 利用
INSERT … ON DUPLICATE KEY UPDATE预插占位记录,防止用户并发领取时产生行锁等待。