pox.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId><!-- redis -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId><!-- spring aop -->
</dependency>

application.yml:

redis:
database: 0
host: localhost
port: 6379
password:
jedis:
pool:
max-active: 200
max-wait: -1
max-idle: 10
min-idle: 0
timeout: 1000

redis配置类:RedisConfig.java​​​​

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; /**
* redis配置类
*
* @author chuhongyun
*/
@Configuration
public class RedisConfig { @Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}

缓存接口:RedisCache.java

import java.lang.annotation.*;

/**
* redis 缓存接口
*
* @author chuhongyun
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisCache { /**
* 键
* @return
*/
String key() default ""; /**
* 过期时间
* @return
*/
long expired() default -1; /**
* 是否为查询操作
* 如果为写入数据库的操作,该值需置为 false
* @return
*/
boolean read() default true;
}

切面程序:RedisCacheAspect.java

import com.alibaba.fastjson.JSON;
import com.zhuyou.common.encryption.ShaUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /**
* redis 切面程序
*
* @author chuhongyun
*/
@Component
@Aspect
public class RedisCacheAspect {
private final static Logger logger = LoggerFactory.getLogger(RedisCacheAspect.class); @Autowired
private RedisTemplate redisTemplate; /**
* 定义切入点,使用了 @RedisCache 的方法
*/
@Pointcut("@annotation(RedisCache)")
public void redisServicePoint() { } /**
* 环绕通知,方法拦截器
*/
@Around("redisServicePoint()")
public Object WriteReadFromRedis(ProceedingJoinPoint point) {
logger.info("<====== 进入 redisCache 环绕通知 ======>");
try {
// 获取RedisCache注解
RedisCache redisCache = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(RedisCache.class);
if (redisCache != null && redisCache.read()) {
//类路径 方法参数 方法名 加密生成redis key
StringBuilder builder = new StringBuilder(point.getTarget().getClass().getName())
.append(JSON.toJSONString(point.getArgs()))
.append(point.getSignature().getName());
String key = RedisKey.I+ ShaUtil.setMD5(builder.toString()); // 查询操作
Object obj = redisTemplate.opsForValue().get(key);
if (obj == null) {
// Redis 中不存在,则从数据库中查找,并保存到 Redis
logger.info("<====== Redis 中不存在该记录,从数据库查找 ======>");
obj = point.proceed();
if (obj != null) {
if (redisCache.expired() > 0) {
redisTemplate.opsForValue().set(key, obj, redisCache.expired(), TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, obj);
}
}
}
return obj;
}
} catch (Throwable ex) {
logger.error("<====== RedisCache 执行异常: {} ======>", ex);
}
return null;
}
}

Redis工具类:RedisService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* Redis工具类
*
* @author chuhongyun
*/
@Component
public class RedisService { @Autowired
private RedisTemplate<String, Object> redisTemplate; // =============================common============================ /**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
boolean result = false;
try {
if (time > 0) {
result = redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} /**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public boolean del(String... key) {
boolean result = false;
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
result = true;
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
result = true;
}
}
return result;
} /**
* 删除缓存 模糊匹配
*
* @param prex 匹配值
*/
public void deleteByPrex(String prex) {
try {
Set<String> keys = redisTemplate.keys(prex + "*");
redisTemplate.delete(keys);
} catch (Exception e) {
e.printStackTrace();
}
} // ============================String============================= /**
* 获取redis中的值
*
* @param key 键
* @return 值
*/
public String get(String key) {
String result = null;
try {
result = redisTemplate.opsForValue().get(key).toString();
} catch (Exception e) {
// e.printStackTrace();
}
return result; } /**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
} /**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map================================= /**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
} /**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
} /**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
} /**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
} /**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
} /**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set============================= /**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} /**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} /**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} /**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list================================= /**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} /**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

目录结构如下:

springboot 2.x整合redis,spring aop实现接口缓存的更多相关文章

  1. 【快学springboot】11.整合redis实现session共享

    前言 这里都是基于前面的项目基础上的.springboot整合redis非常的方便,这也是springboot的宗旨,简化配置.这篇文章就教大家如何使用springboot整合redis来实现sess ...

  2. Spring-AOP SpringBoot自动配置和启动Spring AOP

    SpringBoot 会使用 @Conditional* 注解来进行判断是否需要自动启动 AOP,如果 classpath 下有 spring-aop 的 jar 和有 EnableAspectJAu ...

  3. SpringBoot | 1.3 约定编程Spring AOP

    前言 前面聊过Spring的一个很重要的概念,IoC控制反转,接下来就是AOP了: 1. AOP切面编程 面向切面编程,是利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度 ...

  4. Spring AOP 动态代理 缓存

    Spring AOP应用:xml配置及注解实现. 动态代理:jdk.cglib.javassist 缓存应用:高速缓存提供程序ehcache,页面缓存,session缓存 项目地址:https://g ...

  5. Spring AOP实现接口验签

    因项目需要与外部对接,为保证接口的安全性需要使用aop进行方法的验签; 在调用方法的时候,校验外部传入的参数进行验证, 验证通过就执行被调用的方法,验证失败返回错误信息: 不是所有的方法都需要进行验签 ...

  6. 5.3 Spring5源码--Spring AOP使用接口方式实现

    Spring 提供了很多的实现AOP的方式:Spring 接口方式,schema配置方式和注解. 本文重点介绍Spring使用接口方式实现AOP. 使用接口方式实现AOP以了解为目的. 更好地理解动态 ...

  7. 在 WPF 客户端实现 AOP 和接口缓存

    随着业务越来越复杂,最近决定把一些频繁查询但是数据不会怎么变更的接口做一下缓存,这种功能一般用 AOP 就能实现了,找了一下客户端又没现成的直接可以用,嗐,就只能自己开发了. 代理模式和AOP 理解代 ...

  8. redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)

    平常测试redis操作命令,可能用的是cmd窗口 操作redis,记录一下 java程序操作reids, 操作redis的方法 可以用Jedis ,在springboot 提供了两种 方法操作 Red ...

  9. SpringBoot学习:整合Redis

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 pom.xml添加对redis的依赖: <!-- https://mvnrepos ...

随机推荐

  1. 【MongoDB学习之三】条件操作符

    环境 MongoDB 4.0 CentOS6.5_x64 一.条件操作符 (>) 大于 - $gt (<) 小于 - $lt (>=) 大于等于 - $gte (<= ) 小于 ...

  2. 创建企业级地理数据库报错:ORA-01455

    环境: Oracle Server : 11.2.0.3 (x64) Oracle Client  : 11.1.0.6 (x32) Arcgis Desktop : 10.3 在该环境下执行 &qu ...

  3. SQLite数据库简介和使用

    一.Sqlite简介: SQLite (http://www.sqlite.org/),是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中 ...

  4. 025 SSM综合练习01--数据后台管理系统--功能介绍及数据库表

    1.功能介绍 (1)环境搭建 主要讲解maven工程搭建,以及基于oracle数据库的商品表信息,并完成SSM整合.(2)商品查询 基于SSM整合基础上完成商品查询,要掌握主面页面main.jsp及商 ...

  5. 洛谷P1434滑雪讲解

    题源:[戳这里] 洛谷博客链接:[戳这里] 我觉得这道题主要方法应该有两种: 动态规划 搜索 下面会分别对这两种方法进行简述 一,动态规划法首先的想法是用L(i,j)表示从点(i,j)出发能到达的最长 ...

  6. LeetCode 5073. 进击的骑士(Java)BFS

    题目:5073. 进击的骑士 一个坐标可以从 -infinity 延伸到 +infinity 的 无限大的 棋盘上,你的 骑士 驻扎在坐标为 [0, 0] 的方格里. 骑士的走法和中国象棋中的马相似, ...

  7. golang(三)

    map(声明.初始化和 make) 1. 概念2.map 容量3. 用切片作为 map 的值 概念 map 是引用类型,可以使用如下声明: var map1 map[keytype]valuetype ...

  8. JavaWeb项目之多条件过滤

    相信很多同学在学习java基础之后,面对各种项目还是相当头疼,那今天我将手把手教你学会JavaWeb项目中的多条件过滤,希望你能在与我实战的过程中积累经验,更进一步. 分页查询 需求分析:在列表页面中 ...

  9. phpdocmentor 生成php 开发文档(转载)

    PHPDocumentor是一个用PHP写的工具,对于有规范注释的php程序,它能够快速生成具有相互参照,索引等功能的API文档.老的版本是phpdoc,从1.3.0开始,更名为phpDocument ...

  10. JAVA简易数据连接池Condition

    用Condition和synchronized: import java.sql.Connection; import java.sql.DriverManager; import java.sql. ...