背景
对于一些配置型数据而言,改动不是很频繁,可以在项目启动的时候直接加载到内存,避免需要数据时去查询数据库,造成不必要的io消耗
环境
- springboot
- maven
后端代码
pom依赖
<dependency>
<groupid>com.google.guava</groupid>
<artifactid>guava</artifactid>
<version>31.0.1-jre</version>
</dependency>service层
package com.example.demo.service;
import lombok.extern.slf4j.slf4j;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.stereotype.service;
import com.google.common.collect.maps;
import javax.annotation.postconstruct;
import java.util.hashmap;
import java.util.map;
/**
* @author jn
* @date 2022/2/24 上午9:20
*/
/**解释
被@postconstruct修饰的方法会在服务器加载servlet的时候运行,并且只会被服务器执行一次。
postconstruct在构造函数之后执行,init()方法之前执行。
这里加载的顺序是:springboot的主启动类启动 --> 扫描到evaluationserviceimpl --> 初始化allevaluationmap
--> @postconstruct修饰的方法 --> loadteachingorg()方法
这样当接口注入evaluationserviceimpl后,直接调用evaluationserviceimpl的方法loadteachingorg就可以拿到内存的数据
不需要再走db
*/
@service
@slf4j
public class evaluationserviceimpl {
private logger logger = loggerfactory.getlogger(evaluationserviceimpl.class);
map<long, string> allevaluationmap = maps.newhashmap();
@postconstruct
void init(){
loadteachingorg();
}
public void loadteachingorg(){
//假设:查db得到的数据如下
map<long, string> map = new hashmap<>();
map.put(1l, "评价1");
map.put(2l, "评价2");
map.put(3l, "评价3");
//放入内存
allevaluationmap = map;
}
/**
* 获取当前学期的所有的评价类别
*/
public map<long, string> getallevaluationmap(){
return allevaluationmap;
}
}
controller层
@restcontroller
@requestmapping("/api/evaluation")
public class evaluationcontroller {
@resource
private evaluationserviceimpl evaluationservice;
@requestmapping("all")
public map<long, string> result(){
map<long, string> allevaluationmap = evaluationservice.getallevaluationmap();
system.out.println(allevaluationmap);
return allevaluationmap;
}
}结果:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论