spring @cacheable 注解使用spel表达式
这里主要讲一下复杂的spel表达式,简单的不写了
解析集合
集合需要先自定义一个方法,比如getAuthorsName,然后在注解里通过root.target.getAuthorsName把方法引用进去
public class BookService {
public String getAuthorsName(List<Author> authors) {
return authors.stream().map(Author::getName).collect(Collectors.joining("-"));
}
@Cacheable(value="bookservice", key="'findBook:'+#root.target.getAuthorsName(#authors)")
public Book findBook(List<Author> authors){
// your logic here
}
}
顺便附上root对象的说明
属性名称 | 描述 | 示例 |
---|---|---|
methodName | 当前方法名 | #root.methodName |
method | 当前方法 | #root.method.name |
target | 当前被调用的对象 | #root.target |
targetClass | 当前被调用的对象的class | #root.targetClass |
args | 当前方法参数组成的数组 | #root.args[0] |
caches | 当前被调用的方法使用的Cache | #root.caches[0].name |
使用
@Component
public class CacheKeyGenerator
implements org.springframework.cache.interceptor.KeyGenerator {
@Override
public Object generate(final Object target, final Method method,
final Object... params) {
final List<Object> key = new ArrayList<>();
key.add(method.getDeclaringClass().getName());
key.add(method.getName());
for (final Object o : params) {
key.add(o);
}
return key;
}
}
@Cacheable(value="bookservice",keyGenerator="cacheKeyGenerator")
public Book findBook(List<Author> authors){
// your logic here
}
}
本文作者:leecoders
本文链接:https://www.cnblogs.com/mi520/p/18420856
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步