How to prevent concurrent requests

Set up

  • java, spring

    • spring-data-redis

    • lettuce

  • redis ๊ด€๋ จ ์„ค์ •์ด ๋˜์–ด์žˆ๋‹ค๊ณ  ๊ฐ€์ •

์š”๊ตฌ ์‚ฌํ•ญ

  • 1์ดˆ ๋ฏธ๋งŒ์œผ๋กœ, ๋‹ค์ˆ˜์˜ request๊ฐ€ ์˜จ๋‹ค๊ณ  ๊ฐ€์ •

  • ์ด์ค‘ ํ•˜๋‚˜์˜ ์š”์ฒญ๋งŒ ๋ฐ›์•„๋“ค์ด๊ณ , ๋‚˜๋จธ์ง€๋Š” ์—๋Ÿฌ๋ฅผ ๋˜์ ธ์•ผํ•จ

Use

  • [[INCRBY]]

Example of Java code

@Component
@RequiredArgsConstructor
public class RedisRepository {

	private final RedisTemplate<String, String> redisTemplate;

	public boolean isDuplciated(final String key) {
		var ops = redisTemplate.boundValueOps(key);	
		var result = ops.increment(1L);
		// result can be null
		if (result == null || result == 1L) {
			// this ops wil expire in 1 seconds
			ops.expire(1, TimeUnit.SECONS)
			return false;
		}
		
		return true;
	}
}
  • ๋งจ ์ฒ˜์Œ ์š”์ฒญ์ด ์™”์„ ๊ฒฝ์šฐ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒฐ๊ณผ๋Š” null or 1L

    • ์ด๋Ÿด ๊ฒฝ์šฐ, ํ•ด๋‹น ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋งŒ๋ฃŒ๋ฅผ ์„ค์ •ํ•˜๊ณ , false ๋ฆฌํ„ด

    • ์ฆ‰ ์ค‘๋ณต๋œ ์š”์ฒญ์ด ์•„๋‹˜.

  • ๊ทธ ์™ธ true ๋ฆฌํ„ด

    • ๊ฐ™์€ key 1์ดˆ ๋‚ด ์š”์ฒญ์— ๋Œ€ํ•ด์„œ๋Š”, 2L, 3L, 4L.. ์™€ ๊ฐ™์€ result ๊ฐ€ ๋ฐ˜ํ™˜๋จ

  • ops.expire(1, TimeUnit.SECONS) ์„ค์ •์„ ํ†ตํ•ด์„œ, ๋ฌด๋ถ„๋ณ„ํ•˜๊ฒŒ ์Œ“์ผ ์ˆ˜ ์žˆ๋Š” ์ ์„ ๋ฐฉ์ง€

Last updated