Este tópico descreve o recurso inventory hint fornecido pelo AliSQL. Você pode usar esse recurso em conjunto com os recursos returning e statement queue para confirmar e reverter transações em alta velocidade, aumentando o throughput da sua aplicação.
Informações de contexto
Em casos de uso como promoções relâmpago, a redução de inventário é uma tarefa comum que exige alta concorrência e processamento serializado. O AliSQL utiliza filas e hints transacionais para controlar a concorrência, permitindo confirmar ou reverter transações rapidamente e melhorar o throughput do negócio.
Use o recurso inventory hint para aumentar o desempenho de uma instância do ApsaraDB RDS for MySQL para até 31.000 transações por segundo (TPS). Para isso, atualize dados quentes (hot data) em uma única linha de uma tabela. Para mais informações, consulte Test method and results of hot data updates on a single row.
Pré-requisitos
A instância do RDS executa uma das seguintes versões do MySQL:
MySQL 8.4
MySQL 8.0
MySQL 5.7
MySQL 5.6
Sintaxe
Os seguintes hints foram introduzidos e podem ser usados em instruções selecione, atualize, INSERT e exclua:
-
Para MySQL 5.7, 8.0 e 8.4:
-
Os seguintes hints transacionais foram introduzidos:
COMMIT_ON_SUCCESS: uma transação é confirmada se a execução da instrução à qual esse hint é aplicado for bem-sucedida.
ROLLBACK_ON_FAIL: uma transação é revertida se a execução da instrução à qual esse hint é aplicado falhar.
Sintaxe:
/*+ COMMIT_ON_SUCCESS */ /*+ ROLLBACK_ON_FAIL */Exemplo:
UPDATE /*+ COMMIT_ON_SUCCESS ROLLBACK_ON_FAIL */ T SET c = c - 1 WHERE id = 1; -
O hint condicional TARGET_AFFECT_ROW(NUMBER) foi introduzido.
Após aplicar o hint condicional à instrução atual, a execução só será bem-sucedida quando o número de linhas afetadas for igual ao número especificado nesse hint.
Sintaxe:
/*+ TARGET_AFFECT_ROW(NUMBER) */Exemplo:
UPDATE /*+ TARGET_AFFECT_ROW(1) */ T SET c = c - 1 WHERE id = 1;
-
-
MySQL 5.6
A sintaxe dos hints no MySQL 5.6 é semelhante à sintaxe dos hints em MySQL 5.7 and MySQL 8.0. A única diferença é que não é necessário incluir os hints do MySQL 5.7 e MySQL 8.0 em comentários.
Exemplo:
UPDATE COMMIT_ON_SUCCESS ROLLBACK_ON_FAIL T SET c = c - 1 WHERE id = 1; UPDATE TARGET_AFFECT_ROW(1) T SET c = c - 1 WHERE id = 1;
Notas de uso
Os hints devem ser seguidos por nomes de tabelas.
Quando um hint usado em uma transação entra em vigor, ele aciona uma confirmação automática da transação. Portanto, coloque o hint na última instrução SQL da transação.
-
Os hints transacionais não suportam o modo autocommit. Se você usar um hint transacional em uma instrução executada no modo autocommit, um erro será relatado. Exemplo:
mysql> UPDATE /*+ commit_on_success rollback_on_fail target_affect_row(1) */ t -> SET col1 = col1 + 1 -> WHERE id = 1; ERROR 7531 (HY000): Inventory transactional hints didn't allowed in autocommit mode -
Os hints transacionais não podem ser usados em subinstruções. O uso de um hint transacional em uma subinstrução resulta em erro. Exemplo:
mysql> CREATE TRIGGER tri_1 -> BEFORE INSERT ON t -> FOR EACH ROW -> BEGIN -> INSERT /*+ commit_on_success */ INTO t1 VALUES (1); -> end// mysql> INSERT INTO t VALUES (2, 1); ERROR HY000: Inventory transactional hints didn't alllowed in stored procedure -
Os hints condicionais não podem ser usados em instruções selecione ou EXPLAIN. O uso de um hint condicional nessas instruções resulta em erro. Exemplo:
mysql> EXPLAIN UPDATE /*+ commit_on_success rollback_on_fail target_affect_row(1) */ t -> SET col1 = col1 + 1 -> WHERE id = 1; ERROR 7532 (HY000): Inventory conditional hints didn't match with resultNotaEspecifique um número inválido em TARGET_AFFECT_ROW e verifique se o sistema relata erros:
mysql> EXPLAIN UPDATE /*+ commit_on_success rollback_on_fail target_affect_row(-1) */ t -> SET col1 = col1 + 1 -> WHERE id = 1; +----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+ | 1 | UPDATE | t | NULL | range | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | Using where | +----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+ 1 row in set, 2 warnings (0.00 sec) mysql> show warnings; +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------+ | Level | Code | Message | +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------+ | Warning | 1064 | Optimizer hint syntax error near '-1) */ t set col1=col1+1 where id =1' at line 1 | | Note | 1003 | update /*+ COMMIT_ON_SUCCESS ROLLBACK_ON_FAIL */ `test`.`t` set `test`.`t`.`col1` = (`test`.`t`.`col1` + 1) where (`test`.`t`.`id` = 1) | +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec)
Uso em conjunto com o recurso returning
Use o recurso inventory hint em conjunto com o recurso returning para permitir que o sistema retorne conjuntos de resultados em tempo real. Para mais informações, consulte Returning. Exemplo:
mysql> CALL dbms_trans.returning("*", "update /*+ commit_on_success rollback_on_fail target_affect_row(1) */ t
set col1=col1+1 where id=1");
+----+------+
| id | col1 |
+----+------+
| 1 | 13 |
+----+------+
1 row in set (0.00 sec)
mysql> CALL dbms_trans.returning("*", "insert /*+ commit_on_success rollback_on_fail target_affect_row(1) */ into
t values(10,10)");
+----+------+
| id | col1 |
+----+------+
| 10 | 10 |
+----+------+
1 row in set (0.01 sec)
Uso em conjunto com o recurso statement queue
Use o recurso inventory hint em conjunto com o recurso statement queue para que o sistema enfileire as instruções. Para mais informações, consulte Statement queue. Exemplo:
mysql> UPDATE /*+ ccl_queue_field(id) commit_on_success rollback_on_fail target_affect_row(1) */ t
-> SET col1 = col1 + 1
-> WHERE id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> UPDATE /*+ ccl_queue_value(1) commit_on_success rollback_on_fail target_affect_row(1) */ t
-> SET col1 = col1 + 1
-> WHERE id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0