前言:
为了防止每一次数据交互都直接落地到数据库(会造成数据库连接池的资源浪费等),需要将一些实时性不是很强的数据作为缓存,快速的返回。依然采用了Spring AOP特性实现了“无感知”的数据缓存。
自定义注解:
package com.menghao.cache.annotation;
import com.menghao.cache.support.CacheKeyType;
import java.lang.annotation.*;
/**
* <p>Todo 用作数据查询,默认缓存一天(可自定义).<br>
* <p>可自定义缓存key值,默认采用入参解析方式.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CacheQuery {
/**
* 缓存Key
*/
String cacheKey();
/**
* @see CacheKeyType
*/
CacheKeyType type() default CacheKeyType.ARGS;
/**
* 缓存时间
*/
int cacheTime() default 60 * 60 * 24;
}
package com.menghao.cache.annotation;
import com.menghao.cache.support.CacheKeyType;
import java.lang.annotation.*;
/**
* <p>Todo 用作数据删除,同步删除缓存数据.<br>
* <p>可自定义缓存key值,默认采用入参解析方式.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CacheRemove {
/**
* 缓存Key
*/
String cacheKey();
/**
* @see CacheKeyType
*/
CacheKeyType type() default CacheKeyType.ARGS;
}
package com.menghao.cache.annotation;
import com.menghao.cache.support.CacheKeyType;
import java.lang.annotation.*;
/**
* <p>Todo 用作数据插入/更新.<br>
* <p>可自定义缓存key值,默认采用对象成员变量解析方式.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CacheSet {
/**
* 缓存Key
*/
String cacheKey();
/**
* @see CacheKeyType
*/
CacheKeyType type() default CacheKeyType.ATTRIBUTE;
/**
* 缓存时间,默认24小时
*/
int cacheTime() default 60 * 60 * 24;
}
3种注解对应了增删改查(其中@CacheQuery对应查询,@CacheSet对应了插入和更新,@CacheRemove对应删除)。注解的公有参数cacheKey,用于用户自定义缓存的key值,为了确保key值与数据唯一对应性,需要动态解析key值,因此默认采用了解析形似 “{xxx}”的方式。
- 如果其中为数字,就作为入参数组索引获取对应的值,并替换{argIndex}
- 如果其中为字母,就从返回的对象中获取对应名称的成员变量值,并替换{attribute}
cacheKey解析:
package com.menghao.cache.support;
import com.menghao.cache.exception.CacheKeyParseException;
/**
* <p>Todo 解析不同的key命名规则.<br>
*
* @author menghao.
* @version 2017/12/5.
*/
public interface CacheKeyParse<T, V> {
/**
* 解析key
*
* @param key 原值(默认开闭符号为"{}")
* @return 解析后参数集合
* @throws CacheKeyParseException
*/
String parseKey(String key, V obj) throws CacheKeyParseException;
/**
* 解析key
*
* @param key 原值
* @param open 开符号
* @param close 闭符号
* @return 解析后参数集合
* @throws CacheKeyParseException
*/
String parseKey(String key, V obj, String open, String close) throws CacheKeyParseException;
}
package com.menghao.cache.support;
import com.menghao.cache.exception.CacheKeyParseException;
import java.util.List;
/**
* <p>Todo 抽象实现类,使用模版模式.<br>
*
* @author menghao.
* @version 2017/12/5.
*/
public abstract class AbstractCacheKeyParse<T, V> implements CacheKeyParse<T, V> {
@Override
public String parseKey(String key, V obj) throws CacheKeyParseException {
return parseKey(key, obj, "{", "}");
}
@Override
public String parseKey(String cacheKey, V obj, String open, String close) throws CacheKeyParseException {
// 正则表达式解析
String regEx = "\\" + open + "(\\w+)\\" + close + "";
try {
List<T> indexList = keys(cacheKey, regEx);
List<String> values = values(obj, indexList);
for (String value : values) {
cacheKey = cacheKey.replaceFirst(regEx, value);
}
return cacheKey;
} catch (Exception e) {
throw new CacheKeyParseException("解析cacheKey出现异常");
}
}
abstract List<T> keys(String cacheKey, String regEx) throws CacheKeyParseException;
abstract List<String> values(V args, List<T> keys) throws IllegalAccessException;
}
package com.menghao.cache.support;
import com.menghao.cache.exception.CacheKeyParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Todo 用于解析参数值.<br>
* <p>例如:cacheKey = "user-{0}",就会将入参数组所因为"0"的值替换{0}.<br>
*
* @author menghao.
* @version 2017/12/5.
*/
public class CacheKeyArgsParse extends AbstractCacheKeyParse<Integer, List> {
@Override
public List<Integer> keys(String cacheKey, String regEx) throws CacheKeyParseException {
Pattern p = Pattern.compile(regEx);
try {
Matcher m = p.matcher(cacheKey);
List<Integer> list = new ArrayList<Integer>();
while (m.find()) {
list.add(Integer.parseInt(m.group(1)));
}
return list;
} catch (Exception e) {
throw new CacheKeyParseException("解析cacheKey出现异常");
}
}
@Override
List<String> values(List args, List<Integer> keys) {
List<String> values = new ArrayList<String>(keys.size());
for (Integer index : keys) {
values.add(args.get(index).toString());
}
return values;
}
}
package com.menghao.cache.support;
import com.menghao.cache.exception.CacheKeyParseException;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Todo 用于解析对象成员变量值.<br>
* <p>例子:cacheKey = "user-{id}",会将对象的"id"变量的值替换{id}.<br>
*
* @author menghao.
* @version 2017/12/5.
*/
public class CacheKeyParamsParse extends AbstractCacheKeyParse<String, Object> {
@Override
List<String> keys(String cacheKey, String regEx) throws CacheKeyParseException {
Pattern p = Pattern.compile(regEx);
try {
Matcher m = p.matcher(cacheKey);
List<String> list = new ArrayList<String>();
while (m.find()) {
list.add(m.group(1));
}
return list;
} catch (Exception e) {
throw new CacheKeyParseException("解析cacheKey出现异常");
}
}
@Override
List<String> values(Object object, List<String> keys) throws IllegalAccessException {
List<String> values = new ArrayList<String>(keys.size());
for (String paramName : keys) {
// 反射
Field field = ReflectionUtils.findField(object.getClass(), paramName);
ReflectionUtils.makeAccessible(field);
values.add(field.get(object).toString());
}
return values;
}
}
cacheKey解析运用了模版模式,通过正则表达式解析用户自定义的cacheKey值,返回解析后的cacheKey。对应上述的两种解析方式。
缓存Manager:
package com.menghao.cache.support;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* <p>Todo 目前仅实现了Redis缓存.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
public class RedisCacheManager implements CacheManager {
private JedisPool jedisPool;
public RedisCacheManager(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
@Override
public Object getCache(String key) throws IOException {
Jedis jedis = jedisPool.getResource();
try {
String s = jedis.get(key);
if (null == s) {
return null;
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(s.getBytes());
HessianInput input = new HessianInput(byteArrayInputStream);
return input.readObject();
} finally {
jedis.close();
}
}
@Override
public Long removeCache(String key) {
Jedis jedis = jedisPool.getResource();
try {
return jedis.del(key);
} finally {
jedis.close();
}
}
@Override
public void setCache(String key, Object value, int cacheTime) throws IOException {
Jedis jedis = jedisPool.getResource();
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
HessianOutput output = new HessianOutput(byteArrayOutputStream);
output.writeObject(value);
jedis.set(key.getBytes(), byteArrayOutputStream.toByteArray());
jedis.expire(key, cacheTime);
} finally {
jedis.close();
}
}
}
提供缓存操作数据的统一接口,目前仅实现了Redis作为缓存的方案,其中使用Hessian作为对象的序列化与反序列化,使用Jedis作为Redis的客户端实现。
注意:使用Jedis时,在操作完后一定要记得close释放连接!
AOP增强:
package com.menghao.cache.aop;
import com.menghao.cache.annotation.CacheQuery;
import com.menghao.cache.exception.CacheKeyParseException;
import com.menghao.cache.support.CacheKeyParse;
import com.menghao.cache.support.CacheKeyType;
import com.menghao.cache.support.CacheManager;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* <p>Todo @CacheQuery注解增强.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
@Aspect
public class CacheQueryAspect {
@Autowired
@Qualifier("cacheKeyArgsParse")
private CacheKeyParse cacheKeyArgsParse;
@Autowired
private CacheManager cacheManager;
@Pointcut("@annotation(com.menghao.cache.annotation.CacheQuery)")
public void method() {
}
@Around("method() && @annotation(cacheQuery)")
public Object around(ProceedingJoinPoint joinPoint, CacheQuery cacheQuery) throws CacheKeyParseException {
Assert.notNull(cacheQuery, "注解不能为null");
String cacheKey = cacheQuery.cacheKey();
if (CacheKeyType.ARGS.equals(cacheQuery.type())) {
List<Object> objectList = Arrays.asList(joinPoint.getArgs());
cacheKey = cacheKeyArgsParse.parseKey(cacheKey, objectList);
}
Object o = null;
try {
o = cacheManager.getCache(cacheKey);
} catch (IOException e) {
e.printStackTrace();
}
if (null != o) {
return o;
}
try {
o = joinPoint.proceed();
if (null != o) {
cacheManager.setCache(cacheKey, o, cacheQuery.cacheTime());
return o;
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
就拿@CacheQuery注解方法增强来说明,@Pointcut指定增强方法特征,@Around环绕增强,使用“&& @annotation(cacheQuery)”可以将注解作为入参传入增强方法,以获取用户自定义的cacheKey等值,如果缓存中不存在要查询的数据,就使用ProceedingJoinPoint的proceed方法执行“被增强的方法”,并获取方法的返回值,然后放入缓存。
客户端使用:
<dependency>
<groupId>com.menghao</groupId>
<artifactId>aop-cache</artifactId>
<version>1.0</version>
</dependency>
menghao.cache.enable = true
menghao.cache.type = redis
spring.redis.host = # redis服务端Ip
package com.menghao.cloud.service;
import com.menghao.cache.annotation.CacheQuery;
import com.menghao.cache.annotation.CacheRemove;
import com.menghao.cache.annotation.CacheSet;
import com.menghao.cloud.entity.UserEntity;
import com.menghao.cloud.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>Todo UserService.<br>
*
* @author menghao.
* @version 2017/12/2.
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@CacheQuery(cacheKey = "user-{0}")
public UserEntity findUser(Integer id) {
return userRepository.queryByProperty(UserEntity.builder().id(id).build());
}
@CacheSet(cacheKey = "user-{id}")
@Transactional
public UserEntity addUser(UserEntity userEntity) {
return userRepository.save(userEntity);
}
@CacheRemove(cacheKey = "user-{0}")
public void deleteUser(Integer id) {
userRepository.delete(id);
}
}
总结:
目前仅实现了基本功能:通过日志打印,可以看出24小时内(默认缓存时间),仅在第一次查询时打印了查询语句,插入/更新/删除数据也能同步更新缓存。但不足在于没有考虑高并发情况,多个查询请求同时发送可能会导致不止一个请求落地到后端数据库。