Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the preloading data of SpringBoot Program

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to realize the preloading data of SpringBoot program". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to realize the preloading data of SpringBoot program" can help you solve the problem.

Brief introduction

In the actual development process of a project, there is sometimes a need to load part of the data into the cache before the application is started to provide services.

Applicable scenario

Preload application-level data into the cache: such as dictionary data, common business data

System preheating

Heartbeat detection: scenarios such as accessing an external service interface after the system is started

Common methods

ApplicationEvent

CommandLineRunner

ApplicationRunner

ApplicationEvent

The application event is the publish-subscribe model. After the system starts up, register an event with the application, and once the listener hears the release of the event, he can do some business logic processing.

Since it is a publish-subscribe model, subscribers can be either one or more.

Define eventimport org.springframework.context.ApplicationEvent;public class CacheEvent extends ApplicationEvent {public CacheEvent (Object source) {super (source);}} define listenerimport lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.stream.Collectors @ Slf4j@Componentpublic class CacheEventListener implements ApplicationListener {@ Autowired private MaskingService maskingService; @ Autowired private RedisCache redisCache; @ Override public void onApplicationEvent (CacheEvent cacheEvent) {log.debug ("CacheEventListener-start"); List maskings = maskingService.selectAllSysMaskings (); if (! CollectionUtils.isEmpty (maskings)) {log.debug ("CacheEventListener-data-not-empty") Map cacheMap = maskings.stream () .collect (Collectors.groupingBy (SysMasking::getFieldKey)); cacheMap.keySet () .forEach (x-> {if (StringUtils.isNotEmpty (x)) {log.debug ("CacheEventListener-x= {}", x); List list = cacheMap.get (x) Long count= redisCache.setCacheList (RedisKeyPrefix.MASKING.getPrefix () + x, list); log.debug ("CacheEventListener-count= {}", count);} else {log.debug ("CacheEventListener-x-is-empty");}}) } else {log.debug ("CacheEventListener-data-is-empty");} log.debug ("CacheEventListener-end");}} register event@Slf4j@SpringBootApplication (exclude = {DataSourceAutoConfiguration.class}) public class BAMSApplication {public static void main (String [] args) {ConfigurableApplicationContext context = SpringApplication.run (BAMSApplication.class, args); log.debug ("app-started") Context.publishEvent (new CacheEvent ("handle cache events");}} CommandLineRunner

By implementing the CommandLineRunner interface, you can call back to the specified method after the application has been started.

Package com.ramble.warmupservice.runner;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;@Slf4j@Componentpublic class CacheCommandLineRunner implements CommandLineRunner {@ Override public void run (String... Args) throws Exception {log.debug ("CacheCommandLineRunner-start"); log.debug ("CacheCommandLineRunner- parameter = {}", args); / / inject the service service to obtain the data that needs to be cached / / inject redisTemplate, and store the data to be cached in redis log.debug ("CacheCommandLineRunner-end");}} ApplicationRunner

Similar to CommandLineRunner, except that the parameters are encapsulated.

Package com.ramble.warmupservice.runner;import com.alibaba.fastjson.JSON;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.stereotype.Component;@Slf4j@Componentpublic class CacheApplicationRunner implements ApplicationRunner {@ Override public void run (ApplicationArguments args) throws Exception {log.debug ("CacheApplicationRunner-start"); log.debug ("CacheApplicationRunner- parameter = {}", JSON.toJSONString (args)) / / inject business service, get the data that needs to be cached / / inject redisTemplate, store the data that needs to be cached in redis log.debug ("CacheApplicationRunner-end");}} Test

The above code starts in idea. If there are no parameters, the output is as follows:

2022-04-28 15 c.r.w.WarmupServiceApplication 44 Started WarmupServiceApplication in 00.981 INFO 1160-[main] c.r.w.WarmupServiceApplication: Started WarmupServiceApplication in 1.335 seconds (JVM running for 2.231)

2022-04-28 15 c.r.w.runner.CacheApplicationRunner 4414 00.982 DEBUG 1160-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner-start

2022-04-28 15 c.r.w.runner.CacheApplicationRunner 44displacement 01.025 DEBUG 1160-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner- parameter = {"nonOptionArgs": [], "optionNames": [], "sourceArgs": []}

2022-04-28 15 c.r.w.runner.CacheApplicationRunner 4418 01.025 DEBUG 1160-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner-end

2022-04-28 15 c.r.w.runner.CacheCommandLineRunner 4418 01.025 DEBUG 1160-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner-start

2022-04-28 15 c.r.w.runner.CacheCommandLineRunner 4418 01.026 DEBUG 1160-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner- parameter = {}

2022-04-28 15 c.r.w.runner.CacheCommandLineRunner 4414 01.026 DEBUG 1160-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner-end

2022-04-28 15 c.r.w.listener.CacheEventListener 4414 01.026 DEBUG 1160-[main] c.r.w.listener.CacheEventListener: CacheEventListener-start

2022-04-28 15 c.r.w.listener.CacheEventListener 44displacement 01.026 DEBUG 1160-[main] c.r.w.listener.CacheEventListener: CacheEventListener- parameter = ApplicationEvent-- > cache system data

2022-04-28 15 c.r.w.listener.CacheEventListener 4414 01.029 DEBUG 1160-[main] c.r.w.listener.CacheEventListener: CacheEventListener-end

Disconnected from the target VM, address: '127.0.0.1 transport:' socket'

Process finished with exit code 130

If you start using java-jar xxx.jar-- server.port=9009, enter the following:

05.327 INFO 9916-[main] c.r.w.WarmupServiceApplication: Started WarmupServiceApplication in 1.78 seconds (JVM running for 2.116)

2022-04-28 16 c.r.w.runner.CacheApplicationRunner 02VR 05.329 DEBUG 9916-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner-start

2022-04-28 16 c.r.w.runner.CacheApplicationRunner 02VR 05.393 DEBUG 9916-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner- parameter = {"nonOptionArgs": [], "optionNames": ["server.port"], "sourceArgs": ["--server.port=9009"]}

2022-04-28 16 c.r.w.runner.CacheApplicationRunner 02VR 05.395 DEBUG 9916-[main] c.r.w.runner.CacheApplicationRunner: CacheApplicationRunner-end

2022-04-28 16 c.r.w.runner.CacheCommandLineRunner 02VR 05.395 DEBUG 9916-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner-start

2022-04-28 16 c.r.w.runner.CacheCommandLineRunner 02VR 05.395 DEBUG 9916-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner- parameter =-- server.port=9009

2022-04-28 16 c.r.w.runner.CacheCommandLineRunner 02VR 05.395 DEBUG 9916-[main] c.r.w.runner.CacheCommandLineRunner: CacheCommandLineRunner-end

2022-04-28 16 c.r.w.listener.CacheEventListener 02VR 05.395 DEBUG 9916-[main] c.r.w.listener.CacheEventListener: CacheEventListener-start

2022-04-28 16 c.r.w.listener.CacheEventListener 02V 05.396 DEBUG 9916-[main] c.r.w.listener.CacheEventListener: CacheEventListener- parameter = ApplicationEvent-- > cache system data

2022-04-28 16 c.r.w.listener.CacheEventListener 02VR 05.396 DEBUG 9916-[main] c.r.w.listener.CacheEventListener: CacheEventListener-end

Execution sequence

From the output of the above test, you can see that the order in which the three methods are executed is:

ApplicationRunner--- > CommandLineRunner--- > ApplicationEvent

In addition, if you define multiple runner at the same time, you can specify their priority through order.

This is the end of the content about "how to realize the preloading data of SpringBoot program". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report