基于注解实现redis缓存数据

1,自定义一个注解,参数key是存到redis的key,时间就是缓存多久,默认是0,可以根据自己的业务去顶一个默认值

package com.clpc.un.pafp.statistics.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)//对方法有效
@Retention(RetentionPolicy.RUNTIME)//运行期有效
public @interface CacheFind {
    public String key();
    public int seconds()default 0;//超时时间
}

定义redis配置IP地址,端口等,注入到bean里面

package com.clpc.un.pafp.statistics.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;

@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;

    @Bean
    public Jedis jedis(){
        return new Jedis(host,port);
    }
}

 

2,定义aop切入注解,redis存储过则拿redis的数据,否则就去数据库拿,并且缓存到redis

package com.clpc.un.pafp.statistics.aop;

import com.clpc.un.pafp.statistics.config.CacheFind;
import com.clpc.un.pafp.statistics.config.ObjectMapperUtil;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Arrays;

/**
 * 此类作为缓存的AOP切面类
 */
@Aspect   //标记为切面
@Component  //交给spring管理
public class CacheAop {

    @Value("${Redis.Flag}")
    private Boolean redisFlag;

    @Autowired
    private Jedis jedis;

    /**
     * 实现思路:
     *      1.动态获取key   用户自定义的前缀+用户的参数[0,xx]
     *      2.判断key是否存在
     *      存在: 直接从redis中获取数据 JSON, 需要将json转化为具体对象  按照返回值类型进行转化
     *      不存在: 执行目标方法.获得返回值数据. 将返回值结果转化为JSON格式. 之后保存到缓存中.
     * @param joinPoint
     * @return
     */
    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind){
        Object result = null;
        //1,获取key的前缀
        String key = cacheFind.key();
        //2,获取方法参数
        String argString = Arrays.toString(joinPoint.getArgs());
        key = key+"::"+argString;
        if (redisFlag){
            try {
                //3.判断缓存中是否有数据
                if(jedis.exists(key)){
                    String json = jedis.get(key);
                    //5.获取返回值类型
                    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                    result = ObjectMapperUtil.toObject(json,methodSignature.getReturnType());
                    System.out.println("AOP查询redis缓存");
                }else{
                    //表示缓存中没有数据,执行目标方法
                    result = joinPoint.proceed();
                    String json = ObjectMapperUtil.toJSON(result);
                    //4.判断数据中是否有超时时间
                    if(cacheFind.seconds()>0){
                        jedis.setex(key,cacheFind.seconds(),json);
                    }else{
                        jedis.set(key,json);
                    }
                    System.out.println("AOP执行数据库调用!!!!!");
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new RuntimeException(throwable);
            }
        }else{
            //表示缓存中没有数据,执行目标方法
            try {
                result = joinPoint.proceed();
                System.out.println("未启用redis缓存,查询数据库");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new RuntimeException("AOP方法调用失败");
            }
        }

        return result;
    }
}
ObjectMapperUtil工具类
package com.clpc.un.pafp.statistics.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ObjectMapperUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String toJSON(Object target){
        try {
            return MAPPER.writeValueAsString(target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //将检查异常转化为运行时异常.
            throw new RuntimeException(e);
        }
    }

    public static <T> T toObject(String json,Class<T> targetClass){
        try {
            return MAPPER.readValue(json, targetClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

使用

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是对这三个实验的总结: 1. Spring Boot 整合 Redis 的基本步骤: Spring Boot 提供了对 Redis 的自动配置支持,可以通过配置文件来配置 Redis 连接参数,然后通过@Autowired注解注入 RedisTemplate 来使用 Redis。Spring Boot 整合 Redis 的基本步骤如下: 1)在pom.xml文件中添加 redis 依赖:spring-boot-starter-data-redis。 2)在 application.properties 文件中添加 Redis 连接参数配置,例如: spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= 3)在 Java 代码中使用 RedisTemplate 操作 Redis,例如: @Autowired private RedisTemplate<String, Object> redisTemplate; ValueOperations<String, Object> operations = redisTemplate.opsForValue(); operations.set("key", "value"); Object value = operations.get("key"); 2. Redis 第三方技术的应用: 除了 Redis 本身提供的数据结构和操作命令,还有许多第三方技术可以应用在 Redis 中,例如: 1)Redisson:基于 Redis 的分布式 Java 对象和服务框架,提供了分布式锁、分布式集合等功能。 2)Lettuce:高性能的 Redis 客户端,提供了异步、响应式等多种操作方式,支持 Redis Sentinel 和 Redis Cluster。 3)Jedis:Redis 的 Java 客户端库,提供了 Redis 的基本操作命令。 4)Spring Data Redis:Spring 提供的 Redis 访问框架,提供了对 Redis 的基本操作和缓存支持。 3. 基于注解Redis 缓存实现: Spring Boot 提供了基于注解Redis 缓存实现,可以将方法的返回值缓存Redis 中,下次调用该方法时,如果缓存中存在对应的数据,则直接返回缓存数据,不再执行方法体逻辑。基于注解Redis 缓存实现的基本步骤如下: 1)在 pom.xml 文件中添加 Redis 和 Cache 依赖:spring-boot-starter-data-redis、spring-boot-starter-cache。 2)在 Java 代码中添加 @EnableCaching 注解启用缓存功能。 3)在方法上添加 @Cacheable 注解指定方法返回值需要缓存Redis 中,例如: @Cacheable(value = "userCache", key = "#id") public User getUserById(String id) { return userDao.getUserById(id); } 4)在 application.properties 文件中配置 Redis 连接参数和缓存配置,例如: spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.cache.type=redis 通过使用基于注解Redis 缓存实现,可以提高应用程序的性能和响应速度,减少对数据库的访问,提高系统的并发能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值