Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created June 3, 2019 19:04
Show Gist options
  • Save bdkosher/390f904e9d26d03307e96aebcf779930 to your computer and use it in GitHub Desktop.
Save bdkosher/390f904e9d26d03307e96aebcf779930 to your computer and use it in GitHub Desktop.
mybatis plugin for slowing down specific queries
/**
* For dev purposes only. Intercepts queries and inserts delay to help simulate slow queries.
*/
@Intercepts(
@Signature(
type = StatementHandler.class,
method = "query",
args = {Statement.class, ResultHandler.class}
)
)
@Slf4j
@RequiredArgsConstructor
public class SlowQuerySimulatorPlugin implements Interceptor {
private final Random random = new Random();
/**
* If this value is negative, the actual delay will be randomized to a most its absolute value.
*/
private final int delayMs;
@Override
public Object intercept(Invocation invocation) throws Throwable {
int delay = delayMs > 0 ? delayMs : random.nextInt(Math.abs(delayMs));
StatementHandler handler = (StatementHandler) invocation.getTarget();
if (handler.getBoundSql().getSql().contains("xxx")) { // unique text in query we want to slow down
log.info("Slowing query by {}ms", delay);
log.debug("Query: {}", handler.getBoundSql().getSql());
Thread.sleep(delay);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// intentionally empty
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment