・ DI for enum ・ Memory saving ・ Supports high load with cache function ・ Read only ・ I use it for ranking etc. ・ Supports both Spring Framework and Spring Boot ・ For mappers, please read and set as appropriate. -Initialize when updating context
・ Spring Framework 4.2.9 ・ Spring Boot 2.2.1 · Java 1.8 ・ Windows 10 64bit
SampleRankingSingletonService · Singleton service (enum) that retrieves and retains data -I want to DI mapper with @Autowired, but I can't, so create a separate initialization service. -I think it would be better to add a program to process the data. (Issuing SQL is a heavy load)
public enum SampleRankingSingletonService {
INSTANCE;
//Read timeout value adjustment
public static final int TIMEOUT_SEC = 1800;
private static final Object lock = new Object();
private LocalDateTime queryDate;
//Latest ranking
private List<Sample> latestRanking = new CopyOnWriteArrayList<>();
private SampleMapper sampleMapper;
private SampleRankingSingletonService () {
}
public static SampleRankingSingletonService getInstance() {
return INSTANCE;
}
private boolean isTimeout() {
LocalDateTime execDate = LocalDateTime.now();
if (queryDate == null) { return true; }
LocalDateTime expireDate = queryDate.plusSeconds(TIMEOUT_SEC);
if (expireDate.isBefore(execDate)) {
return true;
}
return false;
}
public synchronized void reload() {
queryDate = LocalDateTime.now();
latestRanking = sampleMapper.selectLatestRanking(); // <-Ranking acquisition SQL issuance
}
//Call before performing data processing
public void initQuery() {
synchronized(lock) {
if (isTimeout() || latestRanking.size() <= 0) {
reload();
}
}
}
public Integer countLatestRanking() {
return latestRanking.size();
}
}
SampleRankingSingletonInitializerService ・ Automatically generated by DI
@Component
public class SampleRankingSingletonInitializerService {
@Autowired
private SampleMapper sampleMapper;
//Set the DI mapper in the singleton service when generating the bean
@PostConstruct
public void init() {
SampleRankingSingletonService.INSTANCE.setSampleMapper(sampleMapper);
}
//Execute the first query when updating the context(Spring Boot gives an error when running with PostConstruct)
@EventListener
public void onContextRefreshedEvent(ContextRefreshedEvent evt) {
SampleRankingSingletonService.INSTANCE.initQuery();
}
public SampleMapper getSampleMapper() {
return sampleMapper;
}
public void setSampleMapper(SampleMapper sampleMapper) {
this.sampleMapper = sampleMapper;
}
}
<bean id="sample.sampleRankingSingletonInitializerService" class="org.sample.SampleRankingSingletonInitializerService">
<property name="sampleMapper" ref="sample.SampleMapper" />
</bean>
It is OK if you set a breakpoint, stop properly after starting the server, and get the data. Thank you for your hard work!
Recommended Posts