CommpressAspect.java 1.83 KB
package com.yoho.search.aop.compress;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.yoho.search.common.utils.HttpServletRequestUtils;
import com.yoho.search.common.utils.SnappyUtils;
import com.yoho.search.models.SearchApiResult;

@Component
@Aspect
public class CommpressAspect {

	// 获取请求的参数
	private boolean isCommpress() {
		HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Map<String, String> paramMap = HttpServletRequestUtils.transParamType(httpServletRequest);
		if(paramMap.containsKey("isDebug")){
			return false;
		}
		return true;
	}


	@Around("@annotation(com.yoho.search.aop.compress.CommpressAble)")
	public Object downGrade(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		final Class<?> returnType = signature.getMethod().getReturnType();
		if (!returnType.isAssignableFrom(SearchApiResult.class)) {
			return pjp.proceed();
		}
		Object result = pjp.proceed();
		if (result == null) {
			return result;
		}
		CommpressAble commpressAble = signature.getMethod().getAnnotation(CommpressAble.class);
		SearchApiResult searchApiResult=(SearchApiResult)result;
		if(commpressAble.isCommpress() && isCommpress()){
			searchApiResult.setData(SnappyUtils.compress(searchApiResult.getData())).setCompress(true);
		}
		return searchApiResult;
	}
}