java注解使用redis缓存,@Aspect aop @interface

/**
 * redis缓存注解
 * @author sunlihuo
 *
 */
@Target({ElementType.METHOD})   
@Retention(RetentionPolicy.RUNTIME)   
@Documented 
public @interface RedisCache {
    public enum Option{ADD,UP,SEL,DEL};

    boolean isArray() default true;
    Class<?> clazz() default Object.class;
    String prefix() default "REDIS_";
    int expireSeconds() default 8000;
    Option option() default Option.SEL;
}

AOP生效果需要配置


/**
 * 缓存处理
 * @author sunlihuo
 *
 */
@Aspect
public class CacheAOP {

    private static final Logger logger = Logger.getLogger(CacheAOP.class);

    private BaseCache baseCache;

    public BaseCache getBaseCache() {
        return baseCache;
    }

    public void setBaseCache(BaseCache baseCache) {
        this.baseCache = baseCache;
    }

    @Around(value = "execution(* ccx.common.service.*.*(..)) && @annotation(cache)")
    public Object around(ProceedingJoinPoint pjd, RedisCache cache) {
        String redisKey = getRedisKey(pjd, cache);
        switch (cache.option()) {
        case SEL:
            return sel(redisKey, pjd);
        case ADD:
            return del(redisKey, pjd);
        case UP:
            return del(redisKey, pjd);
        case DEL:
            return del(redisKey, pjd);
        default:
            break;
        }
        return null;

    }

    /**
     * 查询
     * @param redisKey
     * @param pjd
     * @return
     */
    private Object sel(String redisKey, ProceedingJoinPoint pjd) {
        logger.debug("select redisKey=" + redisKey);

        Object result = null;
        try {
            Object value = baseCache.getObject(redisKey);
            if (null == value) {
                logger.debug("redis baseCache.getObject is null key =" + redisKey);
                result = pjd.proceed();
                baseCache.setObject(redisKey, result);
            } else {
                logger.debug("redis baseCache.getObject is = " + value + " ; key =" + redisKey);
                result = value;
            }
        } catch (Throwable e) {
            logger.error("CacheAOP pjd.proceed error", e);
        }
        return result;
    }

    /**
     * 删除缓存
     * @param redisKey
     */
    private Object del(String redisKey, ProceedingJoinPoint pjd) {
        logger.debug("delete redisKey=" + redisKey);
        baseCache.delete(redisKey);
        Object result = null;
        try {
            result = pjd.proceed();
        } catch (Throwable e) {
            logger.error("CacheAOP pjd.proceed error", e);
        }
        return result;
    }

    /**
     * 取key
     * @param pjd
     * @param cache
     * @return
     */
    private String getRedisKey(ProceedingJoinPoint pjd, RedisCache cache){
        String key = "";
        Object[] args = pjd.getArgs();
        Object obj = args[0];
        if (obj instanceof BaseEntity) {
            long user_id = ((BaseEntity) obj).getUser_id();
            key = "user_id_" + user_id;
        } else if (obj instanceof Long) {
            key = "id_" + (Long) obj;
        } else if (obj instanceof String) {
            key = "id_" + (String) obj;
        }

        String prefix = cache.prefix();
        String redisKey = prefix + key;
        return redisKey;
    }
    /**
     * 前置通知
     * @return 
     */
    private void before(RedisCache cache) {

    }

    /**后置通知
     * 
     */
    private void after() {

    }

    /**
     * 异常通知
     */
    private void throwss() {

    }

    /**
     * 返回通知
     */
    private void result() {

    }

}

附execution 详解 http://blog.csdn.net/sunlihuo/article/details/52701548

AOP生效果需要spring配置

<!--    <aop:aspectj-autoproxy proxy-target-class="true"/> -->
    <aop:aspectj-autoproxy/>  
    <bean class="com.ccx.framework.cache.CacheAOP" >
        <property name="baseCache" ref="redisCache" />
    </bean>
    <bean name="redisCache" class="com.ccx.framework.cache.BaseCache" />

但是最后发现使用注解并没大多的好处

@interface动态注入参数不方便,如注入缓存key

private String getRedisKey(ProceedingJoinPoint pjd, RedisCache cache){
        String key = "";
        Object[] args = pjd.getArgs();
        Object obj = args[0];
        if (obj instanceof BaseEntity) {
            long user_id = ((BaseEntity) obj).getUser_id();

使用如上代码就可以取以key

    @RedisCache(prefix="Card_", option=RedisCache.Option.ADD)
    public boolean add(BaseEntity po) {
        po.setCreate_date(new Date());
        po.setModify_date(new Date());
        return mapper.add(po) > 0 ? true : false;
    }
    @RedisCache(prefix="Card_", option=RedisCache.Option.DEL)
    public boolean del(BaseEntity po) {
        checkCanHandle(po);
        String[] ids = { String.valueOf(po.getId()) };
        return mapper.del(ids) > 0 ? true : false;
    }
    @RedisCache(prefix="Card_", option=RedisCache.Option.UP)
    public boolean update(UserCardInfo po) {
        checkCanHandle(po);
        po.setModify_date(new Date());
        return mapper.update(po) > 0 ? true : false;
    }

    @RedisCache(prefix="Card_")
    public List<UserCardInfo> query(BaseEntity po) {
        PageTools.setDefStartIndex(po);
        Integer total = mapper.queryCount(po);
        po.setTotalRecord(total);
        po.setPageCount((int) Math.ceil((double) total / po.getPageSize()));
        return mapper.query(po);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值