Redis缓存工具类(夏顺辉)

本文介绍如何通过AOP方式利用Redis缓存Spring MVC应用的请求结果,以减轻数据库负担并提高响应速度。文中详细展示了RedisAspect切面类的设计与实现过程,包括如何在方法调用前后检查Redis中是否存在缓存数据,以及如何将结果存储到Redis。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述

1、首先前提是集成了mvn-redis模块

RedisAspect.java代码如下:

/*
 * 文件名:ddd.java
 * 版权:©Copyright by www.sowell-tech.cn
 * 描述:
 * 修改人:Administrator
 * 修改时间:2017年4月17日
 * 修改内容:
 */

package com.sowell.service.impl.catchService;


import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sowell.common.util.StringUtil;

//把这个类声明为一个切面:需要把该类放入到IOC容器中,再声明为一个切面
@Aspect
@Component
public class RedisAspect {



    @Autowired
    RedisService  redisService;

    /**
     * 日志
     */
    private final Logger logger = Logger.getLogger(getClass());

    //坏绕通知:需要携带ProceedingJoinPoint类型的参数
    //环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
    //且环绕通知必须有返回值,返回值即目标方法的返回值。
    @Around("execution(* com.sowell.controller.*Controller.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pjd) {
        Object result = null;
        String methodName = pjd.getSignature().getName();
        Object args = Arrays.asList(pjd.getArgs());

        //执行目标方法
        try {
            logger.info("request channels begin, param{pageNum:" + methodName + ", pageSize:" + args);

            //前置通知
            System.out.println("Arround:The method "+methodName +" begins with "+ args);  

            String key = methodName+"_"+args;

            String jsonStr = redisService.getJsonString(key);
            // 如果数据库里配置的redis服务端中已经存在了这个key对应的数据,那么就将这个数据返回
            if (!StringUtil.isEmpty(jsonStr))
            {
               return jsonStr;
            }
            // 这条语句一直是切面前的逻辑,此方法的返回结果是调用此controller的返回值
            result = pjd.proceed();
            // 下面是切面后的逻辑。如果没有存储这个数据,那么就添加到redis中
            redisService.setString(key,result.toString());

            //后置通知
            System.out.println("Arround:The method "+ methodName+" ends");
        } catch (Throwable e) {
            e.printStackTrace();
            //异常通知
            System.out.println("Arround:The method "+ methodName+"occurs exception:"+e);
            //throw new RuntimeException(e);
            //不抛出异常的话,异常就被上面抓住,执行下去,返回result,result值为null,转换为int
        }
        //返回通知
        System.out.println("Arround:The method "+ methodName+" ends with the Result "+ result);

        return result;
    }

}

RedisService.java代码如下:

package com.sowell.service.impl.catchService;


import org.springframework.stereotype.Service;

import com.sowell.common.util.FastJsonUtils;
import com.sowell.redis.client.RedisClient;
import com.sowell.redis.route.RedisRoute;


/**
 * 此处为类说明
 * @author xiashunhui
 * @version v1.0
 * @since v1.0 2017年4月17日
 * @see 下午3:53:35
 */
@Service
public class RedisService {

    public String setObject(String key ,Object obj)
    {
          // 获取redis客户端
         RedisClient rClient = null;

         String jsonstr =null;
         try
         {
             rClient = RedisRoute.getRedisClient("");
             jsonstr  =FastJsonUtils.toJSONString(obj);

             if (null != rClient)
             {
               rClient.setStr(key, jsonstr);
             }
         }
         catch (Exception e)
         {
            e.printStackTrace();
            return jsonstr;
         }

         return jsonstr;
    }


    public String setString(String key ,String objstr)
    {
          // 获取redis客户端
         RedisClient rClient = null;

         try
         {
             rClient = RedisRoute.getRedisClient("");

             if (null != rClient)
             {
               rClient.setStr(key, objstr);
             }
         }
         catch (Exception e)
         {
            e.printStackTrace();
            return objstr;
         }

         return objstr;
    }


   public String  getJsonString(String key)
    {

       String result =null;
         // 获取redis客户端
        RedisClient rClient = null;
        try
        {   
            //如果参数为"",那么获取到的client也会为null,如果
            rClient = RedisRoute.getRedisClient("");

            if (null != rClient)
            {
                result = rClient.getStr(key);
            }
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }


        return result;

    }


   public String delByKey(String key)
   {
         // 获取redis客户端
        RedisClient rClient = null;

        String jsonstr =null;
        try
        {
            rClient = RedisRoute.getRedisClient("");
            if (null != rClient)
            {
              rClient.delByDataType(key);
            }
        }
        catch (Exception e)
        {
           e.printStackTrace();
           return jsonstr;
        }

        return jsonstr;
   }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值