简体   繁体   中英

Class with datastructure reused by multiple other classes SpringBoot

I am new to Spring Boot and just implemented a normal Spring Boot application with HTTP where endpoints receive data and put in a database. Now I want some data to put in both databases and a class with data structure. Since there will be continuous operations with this data I need to operate with it as a separate process.

@Service
public class RulesManager {
  private HashMap<Integer, Rule> rules = new HashMap<Integer, Rule>();

  public void addRule(Rule rule) {
    // Add rule to the database
  }

  // should be running in the background
  public void updateRules(){
    // Continuous check of rules and update of this.rules HashMap
  }
} 


@SpringBootApplication
public class RulesApplication {

  public static void main(String... args) {
    SpringApplication.run(RulesApplication.class, args);
    // How do I call RulesManager.updateRules() to run in the background and make changes to rules hashmap???
  }
}

So while listening to HTTP requests I want my application to run background process which will never stop and repeat itself. I am not sure how to call that class from the main RulesApplication class so that both http requests and background process were able to make changes to this.rules HashMap. Will be grateful for any tip or advice.

If you are just looking to start a always on process when app starts ( even better when RuleManager gets initialized ), then you should simply create a new thread in the constructor of RuleManager :

methodCalledByConstructor()
{
 new Thread(()->{
        // loop start
        // access and check the hashmap 
        // do what is necessary
        // sleep for a sometime
        // loop end
    }).start();
 }

But if the work is only required when some event occurs, then use observer pattern for more elegant solution.

Try to define a new Thread for example "LocalRulesHandling" and annotate it with @Component and inside this thread add your implementations regarding the rules hashmap.

In the RulesApplication class try to get the spring context and the get the execution thread bean and then start this thread.

ApplicationContext conttext = SpringApplication.run(RulesApplication.class, args); 
LocalRulesHandling handling = context.getBean(LocalRulesHandling.class);            
handling.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM