【问题标题】:Spring @Cacheable not working - MultiThreadingSpring @Cacheable 不起作用 - 多线程
【发布时间】:2020-07-01 02:20:30
【问题描述】:

我有一个 spring 批处理,它使用执行器服务执行多个线程。所有线程都访问下面的方法。我尝试使用@Cacheable 缓存该方法。但它不起作用。每个线程都在不缓存的情况下执行此方法。我使用 sysouts 发现了这一点。更糟糕的是,即使同一个线程在没有缓存的情况下多次进入方法内部(在 for 循环中)。

你能告诉我我在这里做错了什么吗?

   @Cacheable(key="#userID",sync=true)
      public String getPassword(String userID) throws Exceptions{

          
    logger.info("cache not working");   

    SecurityTokenClientResponse password=client.getPassword(req, true, notify.getEnv());
    
    byte[] encryptedPassword=password.getPasswordByteArray();
    
    if (encryptedPassword!=null)
    {
                try {
                    return retrieveCreds(client, encryptedPassword);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                
    
    }else {
    
    password.getBusinessError();
    
    
    }
    
    return null;
    
    }

【问题讨论】:

  • 你不应该在你的方法中使用synchronized吗?
  • 您如何以及从何处调用getPassword 方法以及您使用的是哪个缓存?你确定你使用的是缓存还是 NOOP 缓存(无缓存)?
  • 提供调用代码。

标签: java spring spring-boot executorservice spring-cache


【解决方案1】:

要使 Spring Caching 正常工作,请确保您拥有:

  • 使用@EnableCaching
  • 创建一个 CacheManager bean
  • 告诉你的方法应该使用哪个缓存:@Cacheable(cacheNames = "name of your cache")

例子:

@Bean
public SimpleCacheManager simpleCacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    simpleCacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("myCacheName")));
    return simpleCacheManager;
}

还有:

@Cacheable(key="#userID",sync=true, cacheNames ="myCacheName")
public String getPassword(String userID) throws Exceptions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 2018-09-11
    相关资源
    最近更新 更多