In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how springboot uses aop to achieve interface asynchronism. I hope you will get something after reading this article. Let's discuss it together.
I. Preface
In the project, it is found that there is an interface (excel import data) that takes a long time to deal with the data, because the amount of data is relatively large, and the data verification takes a certain amount of time, so it is decided to use a general method to solve this problem.
Solution: the interface is processed asynchronously through aop, and the front end polls another interface to query the progress.
Goal:
1 Interface async can be realized with a note on the interface (optimization: async can be dynamically controlled by header parameters)
2 one method to update the progress bar
2. Sequence diagram
Third, functional demonstration
4. Key code Controller
@ EnableAsync is a custom annotation update cache progress asyncService.updatePercent (per)
@ EnableAsync @ RequestMapping (value = "test", method = RequestMethod.POST) @ ApiOperation (value = "Interface Test") @ ApiImplicitParams ({@ ApiImplicitParam (name = "num", value = "number", required = true, dataType = "int", paramType = "query", defaultValue = "1")}) public Object demo (Integer num) throws InterruptedException {for (int I = 0; I < 15; iTunes +) {Thread.sleep (1000) / / calculate percentage String per = BigDecimal.valueOf (I) .percent (BigDecimal.valueOf (15), 2, RoundingMode.HALF_DOWN) .toString (); / / update redis cache progress asyncService.updatePercent (per);} Integer b = 100 Return Result.success ("Thread variable value:% s 100 divided by% s", RequestHolder.get (), num, b / num);} AsyncAop import cn.hutool.core.util.IdUtil;import com.asyf.demo.common.Result;import com.asyf.demo.common.pojo.RequestHolder;import com.asyf.demo.service.AsyncService;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around Import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @ Aspect@Component@Slf4jpublic class AsyncAop {@ Autowired private AsyncService asyncService @ Pointcut ("@ annotation (com.asyf.demo.common.aop.EnableAsync)") public void costTimePointCut () {} @ Around ("costTimePointCut ()") public Object around (ProceedingJoinPoint point) throws Throwable {long beginTime = System.currentTimeMillis (); / / request header ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = servletRequestAttributes.getRequest (); RequestHolder.set (request.getHeader ("dateFormat")) / / Asynchronous message String id = IdUtil.simpleUUID (); AsyncMsg asyncMsg = new AsyncMsg (); asyncMsg.setId (id); / / Asynchronous return value Object result = Result.success (asyncMsg); String requestHolder = RequestHolder.get (); / / Asynchronous execution asyncService.async (requestHolder, asyncMsg, point) / / execution duration (Ms) long time = System.currentTimeMillis ()-beginTime; logCostTime (point, time); return result;} private void logCostTime (ProceedingJoinPoint point, long time) {MethodSignature signature = (MethodSignature) point.getSignature (); String className = point.getTarget (). GetClass (). GetName (); String methodName = signature.getName () Log.info ("class: {} method: {} time: {} ms", className, methodName, time);}} AsyncService
Implement the update of asynchronous messages
The progress information transmission of asynchronous message is realized by local thread and redis.
Import cn.hutool.core.exceptions.ExceptionUtil;import com.asyf.demo.common.aop.AsyncMsg;import com.asyf.demo.common.pojo.AsyncHolder;import com.asyf.demo.common.pojo.RequestHolder;import com.asyf.demo.service.AsyncService;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit @ Service@Slf4jpublic class AsyncServiceImpl implements AsyncService {@ Autowired private RedisTemplate redisTemplate; @ Override public void async (String requestHolder, AsyncMsg asyncMsg, ProceedingJoinPoint point) {new Thread (new Runnable () {@ Override public void run () {String id = thread (); / / request thread variable-pass request thread parameter RequestHolder.set (requestHolder) / / Asynchronous message thread variable-pass id to the actual method so that the method update progress AsyncHolder.set (asyncMsg); / / execute method try {redisTemplate.opsForValue () .set (id, asyncMsg, 60, TimeUnit.MINUTES); Object result = point.proceed () AsyncMsg.setResult (result); asyncMsg.setStatus ("0"); redisTemplate.opsForValue (). Set (id, asyncMsg, 60, TimeUnit.MINUTES);} catch (Throwable throwable) {log.error (ExceptionUtil.stacktraceToString (throwable)); asyncMsg.setStatus ("- 1") AsyncMsg.setResult (throwable.getLocalizedMessage ()); redisTemplate.opsForValue (). Set (id, asyncMsg, 60, TimeUnit.MINUTES);}) .start ();} @ Override public void updatePercent (String per) {AsyncMsg asyncMsg = AsyncHolder.get (); asyncMsg.setPercent (per) RedisTemplate.opsForValue (). Set (asyncMsg.getId (), asyncMsg, 60, TimeUnit.MINUTES);}} after reading this article, I believe you have a certain understanding of "how springboot uses aop to achieve interface asynchrony". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!
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.