(9)AOP和Redis登錄案例

1.@Aspect(切面): 通常是一個類,裏面可以定義切入點和通知
2.@Before(“verify()”)標識一個前置增強方法,相當於BeforeAdvice的功能
3.@Pointcut表示式

  • execution:用於匹配方法執行的連接點;
//AOP登錄校驗
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;
    //去掉 && !	SellerUserController此類校驗
    @Pointcut("execution(public * com.imooc.controller.Seller*.*(..))" +
    "&& !execution(public * com.imooc.controller.SellerUserController.*(..))")
    public void verify() {}
    
    //登錄前			
    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查詢cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) {
            log.warn("【登錄校驗】Cookie中查不到token");
            throw new SellerAuthorizeException();
        }

        //去redis裏查詢 get查詢
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            log.warn("【登錄校驗】Redis中查不到token");
            throw new SellerAuthorizeException();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章