foreword
Some blog posts I wrote at work before were not synchronized to the blog. This article may have been written more than a year ago, hoping to give readers some inspiration.
We share a data background for multiple games, and distinguish different games and environments through different configurations. Determine which set of configuration to read by specifying application.properties
.spring.profiles.active
For example, if we need to publish to the prd environment code-named sfish, we can select spring.profiles.active=sfishlyprd
it, and our configuration file is in resources/config 下有
application-sfishlyprd.properites`.
The file is distinguished by gameid:
gameid=sfishlyprd
text
The original scheduled task has only one class, and there are many methods in this class, and each method belongs to a certain project. Then judge by logic similar to the following:
The first step I made to optimize is to classify the methods by project, and the proprietary classes correspond to the corresponding projects. Similar to:
This is just a simple logical division, and does not have much impact on the actual operation, that is to say, even if the current Sfish project, the scheduled tasks of the lytj project are still running.
SpringBoot's scheduled tasks will be mapped to an operating system thread to run, so it is necessary for us to perform further optimization.
- First, we define a parent class, and let the plan classes of these projects inherit this parent class.
public class GameSchedule {
}
public class SfishSchedule extends GameSchedule{
}
- Comment out these project plan classes
@Componet
so that SpringBoot will not automatically load these classes.
- Write a configuration class. The logic is to read the configuration file of the current project to obtain the gameid, and use the gameId to determine which subclass we enable. The current scheduled tasks are all for a certain project. If there are public ones in the future, you can directly add methods to the GameSchedule class.
@Configuration
public class ScheduleConfig {
@Value("${gameid}")
private String gameid;
@Bean
public GameSchedule createSchedule(){
if (gameid.startsWith("sfish") || gameid.startsWith("zfsfish")) {
return new SfishSchedule();
} else if (gameid.startsWith("lytj")) {
return new LytjSchedule();
}
return new GameSchedule();
}
}
When we add new methods in the future, we don’t need to write gameid judgment anymore.
Look back
Now it seems that the code of the above configuration class can be further optimized, but the premise is to unify the naming of various gameids, or use new attributes to distinguish them, for example, after parsing lytj, find it, find it, and LytjSchedule
then sfish
use SfishSchedule
reflection To instantiate the associated class.