1.异步实现发送短信
@RestController
@Slf4j
public class LoginService {
@Autowired
private LoginManage loginManage;
@GetMapping("/login")
public ResponseEntity<String> login(UserEntity userEntity) {
UserEntity dbUser = dbLogin(userEntity);
if (dbUser == null) {
return ResponseEntity.status(500).body("账号或者是密码错误");
}
loginManage.asynLogin(userEntity);
return ResponseEntity.status(200).body("登陆成功");
}
}
@Component
@Slf4j
public class LoginManage {
@Async
public void asynLogin(UserEntity userEntity) {
loginLog(userEntity);
sendSms(userEntity);
sendEmail(userEntity);
}
private UserEntity dbLogin(UserEntity userEntity) {
log.info(">>>1.正在查询数据库登陆<<<");
try {
Thread.sleep(2000);
} catch (Exception e) {
}
return new UserEntity();
}
private void sendSms(UserEntity userEntity) {
log.info(">>>3.异步开始发送短信<<<");
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
private void sendEmail(UserEntity userEntity) {
log.info(">>>4.异步开始发送邮件<<<");
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
2. 异步实现记录请求日志
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class WebLogAspect {
@Pointcut("execution( * com.tostyle.service.*.*(..))")
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable{
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("请求地址 : " + request.getRequestURL().toString());
log.info("HTTP METHOD : " + request.getMethod());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
log.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")
public void doAfterReturning(Object ret) throws Throwable {
log.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();
log.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}