In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how redis distributed locks can solve the problem of form repeated submission. The content is concise and easy to understand, and it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
If the user's network speed is slow and the user clicks the submit button, but does not jump to the new page because of the slow speed, the user will click the submit button again, for example: the user clicks on the order page, when the user clicks the submit button, perhaps because of the speed of the network, the user does not jump to the new page, and the user will click the submit button again, if it has not been processed. At this point, the user will generate two orders, similar to this scenario is called repeated submission.
Use redis's setnx and getset commands to solve the problem of form repeated submission.
1. Introduce redis dependency and aop dependency
Org.springframework.boot spring-boot-starter-redis 1.3.8.RELEASE org.springframework.boot spring-boot-starter-aop
two。 Write methods for locking and unlocking.
/ * * @ author wangbin * @ description redis distributed lock * @ date September 20, 2019 * / @ Componentpublic class RedisLock {private final Logger logger = LoggerFactory.getLogger (RedisLock.class); @ Autowired private StringRedisTemplate redisTemplate / * @ author wangbin * @ description for locking operation (this method is run by a single thread) * @ date 20 September 2019 * @ param key some method requests url plus the user identity in cookie to use md5 encryption to generate * @ param value current time + expiration time (10 seconds) * @ return true indicates that the false table has been locked successfully Indicates that the lock * / public boolean lock has not been acquired (String key String value) {/ / successfully returned true if (redisTemplate.opsForValue () .setIfAbsent (key,value,10, TimeUnit.SECONDS)) {return true } String currentValue = redisTemplate.opsForValue (). Get (key); / / failed to add the lock, and then determine whether the deadlock is caused by the failure of unlocking. If (StringUtils.isNotEmpty (currentValue) & & Long.parseLong (currentValue) < System.currentTimeMillis ()) {/ / acquire the last lock, and reset the lock String oldValue = redisTemplate.opsForValue (). GetAndSet (key, value) If (StringUtils.isNotEmpty (oldValue) & & oldValue.equals (currentValue)) {/ / successfully set the lock to ensure that a single thread runs return true;}} return false } / * * @ author wangbin * @ description to unlock * @ date September 20, 2019 * @ param key a method requests url to generate * @ param value current time + expiration time * @ return * / public void unLock (String key,String value) {try {String currentValue = redisTemplate.opsForValue (). Get (key) If (StringUtils.isNotEmpty (currentValue) & & currentValue.equals (value)) {redisTemplate.delete (key);}} catch (Exception e) {logger.error ("redis distributed lock, unlock exception", e) }} / * @ author wangbin * @ description to unlock * @ date September 20, 2019 * @ param key some method requests url to use md5 encryption to generate * @ return * / public void unLock (String key) {try {String currentValue = redisTemplate.opsForValue (). Get (key) If (StringUtils.isNotEmpty (currentValue)) {redisTemplate.delete (key);}} catch (Exception e) {logger.error ("redis distributed lock, unlock exception", e);}
3. Use the interceptor to determine the lock before the request.
@ Configurationpublic class LoginInterceptor extends HandlerInterceptorAdapter {private final Logger logger = LoggerFactory.getLogger (LoginInterceptor.class); / / the timeout is set to 10 seconds private static final int timeOut = 10000; @ Autowired private StringRedisTemplate stringRedisTemplate; @ Autowired private RedisLock redisLock / * call before request processing (before Controller method call) * interceptor based on URL implementation * @ param request * @ param response * @ param handler * @ return * @ throws Exception * / @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String path = request.getServletPath () If (path.matches (Constants.NO_INTERCEPTOR_PATH)) {/ / unwanted intercept passes directly through return true } else {/ / this is to intercept the things you need to do, such as caching, SESSION, permission judgment, etc. / / determine whether the request is repeatedly submitted if (! redisLock.lock (DigestUtils.md5Hex (request.getRequestURI () + value), String.valueOf (System.currentTimeMillis () + timeOut) {logger.info ("= failed to acquire the lock The request is a repeat submission request ") Return false;} return true;}
4. Use aop to unlock in a post notification.
/ * * @ author wangbin * @ description uses redis distributed locks to solve the problem of repeated form submission * @ date September 20, 2019 * / @ Aspect@Componentpublic class RepeatedSubmit {@ Autowired private RedisLock redisLock; / / define pointcut @ Pointcut ("execution (public * com.kunluntop.logistics.controller..*.* (..)") Public void pointcut () {} / / release the lock @ After ("pointcut ()") public void after () {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = attributes.getRequest (); redisLock.unLock (DigestUtils.md5Hex (request.getRequestURI () + CookieUtils.getCookie (request, "userkey")) after method execution }} the above is how redis distributed locks solve the problem of form repeated submission. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.