3

我想在为 findById(Long id) 方法扩展相同 AbstractService 的多个服务上启用缓存。

所以在我的 applicationContext 我写道:

<!-- cache definitions -->
    <cache:advice id="cacheAdvice" cache-manager="cacheManager">
        <cache:caching cache="refs">
              <cache:cacheable method="findById" key="#root.targetClass + #id"/>
         </cache:caching>
    </cache:advice>

    <aop:config>
        <aop:advisor advice-ref="cacheAdvice" pointcut="execution(* x.y.*.service.reference.*.*(..))"/>
    </aop:config>

问题是我想为方法 findById 上的每个服务调用生成一个唯一键,因为 ID 可以相同(因此有一个类转换异常):

java.lang.ClassCastException: x.y.model.RefSituation  cannot be cast to x.y.model.RefCivility

单元测试 :

public class AbstractReferenceServiceTest extends AbstractBiTest {

    @Inject
    @Named("refSituationServiceClient")
    private RefSituationService refSituationService;

    @Inject
    @Named("refCivilityServiceClient")
    private RefCivilityService refCivilityService;

    @Test
    public void findById() {
        RefSituation situation = refSituationService.findById(1L);
        situation = refSituationService.findById(2L);
        situation = refSituationService.findById(1L);

        RefCivility refCivility = refCivilityService.findById(1L);
        refCivility = refCivilityService.findById(2L);
        refCivility = refCivilityService.findById(1L);
    }
}

两种服务都扩展了 AbstractReferenceService :

public interface RefSituationService extends AbstractReferenceService<RefSituation> {}
public interface RefCivilityService extends AbstractReferenceService<RefCivility> {}

并且 AbstractReferenceService 扩展了一个名为 RestHub 的框架提供的 crudService ( https://github.com/resthub/resthub-spring-stack/blob/master/resthub-common/src/main/java/org/resthub/common/service/ CrudService.java )

但是使用上面的配置我有一个错误:

org.springframework.expression.spel.SpelEvaluationException: EL1030E:(pos 0): The operator 'ADD' is not supported between objects of type 'java.lang.Class' and 'null'
    at org.springframework.expression.spel.ExpressionState.operate(ExpressionState.java:198)
    at org.springframework.expression.spel.ast.OpPlus.getValueInternal(OpPlus.java:97)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:93)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:89)
    at org.springframework.cache.interceptor.ExpressionEvaluator.key(ExpressionEvaluator.java:80)
    at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.generateKey(CacheAspectSupport.java:464)
    at org.springframework.cache.interceptor.CacheAspectSupport.inspectCacheables(CacheAspectSupport.java:291)
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:198)
    at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy175.findById(Unknown Source)

在此先感谢您的帮助。

4

4 回答 4

2

问题是#root.targetClass.name 始终是“CrudService”,要解决您必须的问题:

1-实现自己的 CacheKeyGenerator :

应用程序上下文.xml:

    <bean id="refCacheKeyGenerator" class="x.y.cache.RefCacheKeyGenerator" />

<!-- cache definitions -->
    <cache:advice id="cacheAdvice" key-generator="refCacheKeyGenerator" cache-manager="cacheManager">
        <cache:caching cache="refs">
              <cache:cacheable method="findById"/>
         </cache:caching>
    </cache:advice>

    <aop:config>
        <aop:advisor advice-ref="cacheAdvice" pointcut="execution(* x.y.*.service.reference.*.*(..))"/>
    </aop:config>

爪哇:

public class RefCacheKeyGenerator implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(Object target, Method method, Object... params) {
        final List<Object> key = new ArrayList<>();

        key.add(method.getDeclaringClass().getName());      
        key.add(method.getName());

        List<Class<?>> clazz = ClassUtils.getAllInterfaces(target.getClass());
        if(CollectionUtils.isNotEmpty(clazz)){
            for(Class<?> sClass : clazz){
                if(AbstractReferenceService.class.isAssignableFrom(sClass)){
                    if(!AbstractReferenceService.class.equals(sClass)){
                     key.add(sClass.getName());
                    }
                }
            }
        }
        for (final Object o : params) {
            key.add(o);
        }

        return key;
    }

}

测试 :

public class RefCacheTest extends AbstractTest {

    @Autowired
    private RefSituationService refSituationService;

    @Autowired
    private RefCivilityService refCivilityService;

    @Autowired
    private CacheManager cacheManager;


    @Test
    public void findById() {

        Cache refCache = cacheManager.getCache(MyCache.REFS);
        refCache.setStatisticsEnabled(true);

        assertThat(refSituationService.findById(1L)).isInstanceOf(RefSituation.class);
        assertThat(refSituationService.findById(1L)).isInstanceOf(RefSituation.class);
        assertThat(refSituationService.findById(2L)).isInstanceOf(RefSituation.class);

        assertThat(refCivilityService.findById(1L)).isInstanceOf(RefCivility.class);
        assertThat(refCivilityService.findById(1L)).isInstanceOf(RefCivility.class);
        assertThat(refCivilityService.findById(2L)).isInstanceOf(RefCivility.class);

        System.out.println(refCache.getName() +" - "+ refCache.getStatistics().toString()); 

        assertThat(refCache.getStatistics().getCacheHits()).isEqualTo(2);
        assertThat(refCache.getSize()).isEqualTo(4);
    }
于 2014-02-18T09:04:57.900 回答
0

这里发生的最有可能是+运算符和类型的问题,可能是也可能不是Strings。假设您想要字符串连接(长算术会导致我认为您试图避免的冲突),强制您的关键参数Strings可能会解决问题。翼:

<!-- cache definitions -->
<cache:advice id="cacheAdvice" cache-manager="cacheManager">
    <cache:caching cache="refs">
          <cache:cacheable method="findById" key="#root.targetClass.name + #id.toString()"/>
     </cache:caching>
</cache:advice>
于 2014-02-17T16:19:18.667 回答
0

我现在已经尝试过了,它只与下一个配置一起工作,没有密钥生成器的额外自定义实现:

@Cacheable(value = "lookups", key="T(org.springframework.cache.interceptor.SimpleKeyGenerator).generateKey(#root.target.class, #root.args)")

这里的主要思想包括对象的具体类作为关键部分之一。

于 2015-12-21T13:46:31.543 回答
0

这是创建唯一密钥的更简单方法:

@Cacheable(value = "all-coupons", cacheManager="cacheManagerCompany" , key="#root.method + #this.toString()")
@Override
public List<Coupon> getAllCoupons() {

    return compDBDAO.getCoupons();
}

这个问题的解决方案是使用key="#root.method + #this.toString().

于 2018-07-13T16:05:24.677 回答