0

I want to cache the following getMessagesList method. I want to call one time When user log into the system. Therefor I think caching is the best solution for that. And I need to remove when user log out. How I can do this.

public List<String> getMessagesList(String username)
{  // return messages list in DB by username}

My project was create using Maven 4.0 and Spring MVC. spring version 5.3

Geeth
  • 541
  • 3
  • 12

1 Answers1

0

Assuming you use Spring Security as part of your app, it should be managing your session, and every time you log out, it will create a new session. Unless you had posted this code, I'm not going to be able to help you there. However, assuming you can log in/out, this should be covered already.

As for the cacheing, in general, this sounds like a Database Caching need, which is something that you would use Spring Boot Caching on.

To use this in Spring Boot, you would add the following dependency to maven (or the equivalent in Gradle, etc):

<dependency>
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-cache</artifactId>  
</dependency>
  1. Adjust your application to allow using Cacheing, which can be done by adding the annotation @EnableCaching to your Spring Boot application
@SpringBootApplication
@EnableCaching
public class MyApplication {
...
}
  1. Create a Java Service Object, called something like MessagesService.class:
@CacheConfig(cacheNames={"Messages"})
public class MessagesService {
  
  @Cacheable(value="cacheMessages")
  List<String> getMessages() {
    //access the database to load data here
    ...
  }
  
  ...
}
Justin Grant
  • 123
  • 6
  • My project is Spring MVC, not spring boot. There has no main Application class. That's why I'm asking how to config cashing in the Spring MVC project. – Geeth Feb 22 '22 at 02:26