springboot中的另一个函数如何使用缓存中存储的数据

How to use the data stored in cache for another function in springboot

我创建了一个示例 spring 引导应用程序,它有一个 class“CacheManagement”,其中我有一个函数“getAllValue " 其中 return 我需要缓存其值的客户对象。 class 还有一个函数 checkCache,它使用缓存中的数据。我怎样才能实现这个。有人请帮我解决这个问题。我提供 class 我有 written.PFB class

@Service
public class CacheManagement {
    
    @Cacheable(value = "service",key = "list")
    public Customer getAllValue(){
        Customer customer = new Customer();
        System.out.println("Inside cache");
        customer.setId("1");
        customer.setName("Shilpa");
        return customer;
    }
    
    public String checkCache() {
    Customer cus = getAllValue();
    System.out.println(cus.toString());
    return "1";
    
    }

}

PFB主class:

@SpringBootApplication
public class DemoApplication implements CommandLineRunner{

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Override
    public void run(String... arg0) {
        CacheManagement cacheService = new CacheManagement();
        cacheService.getAllValue();
        cacheService.checkCache();
                
        
        
    }
}

根据我的需要,sysout 语句应该只打印一次,对吗?但我的问题是它打印了两次。意味着来自 checkCache() 方法的 getAllValue() 调用正在调用函数本身而不是从缓存中获取数据. 请帮我解决这个问题。

您的代码存在多个问题。

  1. CacheManagement cacheService = new CacheManagement(); 创建一个实例,它不是 Spring 容器管理的 bean。 Spring 魔法在这里不起作用。您应该获得 cacheManagement 的 Spring 容器管理的 bean,用于所有 Spring 框架对 kickin 的支持。
@SpringBootApplication
@EnableCaching
public class DemoApplication implements CommandLineRunner {
    @Autowired
    CacheManagement cacheService;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... arg0) {
        cacheService.getAllValue();
        cacheService.checkCache();
    }
}

2.Assuming 您已使用 @EnableCaching ( Refer here )

启用缓存
@SpringBootApplication
@EnableCaching
public class DemoApplication implements CommandLineRunner{
...
}

Spring 缓存在 Spring AOP 的帮助下工作,Spring AOP 在代理上工作。从相同 class(此处 checkCache())的方法中调用 getAllValue() 称为自调用。 Spring 在这种情况下,AOP 将无法通知方法调用,因为它不会通过代理,因此缓存逻辑无法工作。

要详细了解这个概念,请参阅官方 spring 参考文档:Understanding AOP Proxies。通读以 开头的部分,这里要理解的关键是 main(..)

中的客户端代码

您的问题的解决方法是确保 checkValue() 调用通过代理,以便返回缓存的结果。由于您需要将方法 (checkValue()) 作为同一个 bean 的一部分,一个自引用就可以了。

您必须通读关于同一主题的 official documentation 才能理解其中的含义。以 开头的部分从 4.3 开始,@Autowired 还考虑了用于注入的自引用 ..

以下代码应该可以解决您的问题

@Service
public class CacheManagement {

    @Autowired
    CacheManagement self;
    
    @Cacheable(value = "service",key = "list")
    public Customer getAllValue(){
        Customer customer = new Customer();
        System.out.println("Inside cache");
        customer.setId("1");
        customer.setName("Shilpa");
        return customer;
    }
    
    public String checkCache() {
    Customer cus = self.getAllValue();
    System.out.println(cus.toString());
    return "1";
    
    }

}

阅读有关缓存的更多信息here