SpringBoot集成Redis使用Jedis开发

1.引入jar

<!--SpringBoot的aop编程-->
 <dependency>
 	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>

<!--加入jedis-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

2.编写自定义注解类 RedisCache,被该注解定义的类都自动实现AOP

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 RedisCache {
}

3.将Jedis交由Spring工厂管理

//第一种redis写死
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

@Configuration
public class RedisConf {
    @Bean
    public Jedis getJedis(){
        return new Jedis("192.168.226.144",6379);
    }
}
//第二种交由工厂
public class JedisConfig extends CachingConfigurerSupport {
    //日志
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    //读取配置文件中redis配置
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    //Bean工厂管理jedis
    @Bean
    public Jedis getJedis() {
        Jedis jedis = new Jedis(host, port);
        jedis.auth(password);
        logger.info("ip为:"+host,"端口为:"+port,"密码为:"+password);
        return jedis;
    }
}

4.Spring AOP实现监控所有被自定义注解@RedisCache注解的方法缓存

@Configuration
@Aspect
public class RedisCommonCache {
    @Autowired
    private Jedis jedis;
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    //将业务放入缓存
    @Around("execution(* com.zxl.service.*.*(..))")
    public Object cache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        logger.info("method为:"+method);
        String methodName = method.getName();
        logger.info("methodName为:"+methodName);
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        logger.info("className为:"+className);
        StringBuilder builder = new StringBuilder();
        builder.append(methodName).append(":");
        Object[] args = proceedingJoinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            builder.append(arg);
            if (i == args.length - 1) {
                break;
            }
            builder.append(":");
        }
        String valueKey = builder.toString();
        boolean b = method.isAnnotationPresent(RedisCache.class);
        /*如果有这个注解  去缓存中取数据*/
        Object result = null;
        if (b) {
            //判断当前这个方法在缓存中是否存在
            //存在
            if (jedis.hexists(className, valueKey)) {
                String s = jedis.hget(className, valueKey);
                result = JSONObject.parse(s);
            } else {
                //不存在
                result = proceedingJoinPoint.proceed();
                jedis.hset(className, valueKey, JSONObject.toJSONString(result));
            }
        } else {
            proceedingJoinPoint.proceed();
        }
        jedis.close();
        return result;
    }
    //增删改操作会先将对应的缓存从redis中删除,再重新查询数据库并重新存入redis缓存
    @After("execution(* com.zxl.service.*.*(..)) && !execution(* com.zxl.service.*.select*(..))")
    public void after(JoinPoint joinPoint){
        String name = joinPoint.getTarget().getClass().getName();
        jedis.del(name);
        jedis.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值