package com.elab.redis.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 实现缓存的拦截器
 * @author ： liukx
 * @time ： 2020/7/9 - 20:08
 */
public class LockCacheInterceptor implements MethodInterceptor, Serializable {
    @Autowired
    private List<ICacheProcessService> cacheProcessServices;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object proceed = null;
        if (invocation instanceof ReflectiveMethodInvocation) {
            ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;
            Method method = invocation.getMethod();
            for (int i = 0; i < cacheProcessServices.size(); i++) {
                ICacheProcessService cache = cacheProcessServices.get(i);
                if (cache.subscribe(method)) {
                    proceed = cache.invokeWithinTransaction(methodInvocation);
                }
            }
            return proceed;
        }
        return null;
    }
}
