1. 程式人生 > 資料庫 >SpringBoot整合Redis使用Jedis開發

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();
    }
}