springboot启动后马上调用类方法

本文介绍了一种使用静态Map作为自定义缓存的方法,通过在项目启动时加载固定不变且频繁请求的数据,减少数据库的压力,提高系统响应速度。文章详细展示了如何创建自定义缓存类并实现在Spring Boot应用中自动加载数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于有些简单项目不涉及redis但又要频繁向数据库请求数据的时候,可以考虑自己建立一个静态map,在项目运行的时候把一部分固定不变又频繁请求的数据放入这个map中。

首先,创建一个自定义缓存的类(静态map)

实现CommandLineRunner接口,重写run方法(实现项目运行完成就马上执行某个方法,主题来了)

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.jxgp.modules.gpjc.service.CityService;
import com.jxgp.modules.gpjc.vo.CityTree;
import com.jxgp.modules.tb.entity.CompanyCatalogueEntity;
import com.jxgp.modules.tb.service.CompanyCatalogueService;


/**
 * 自定义缓存
 * */
@Component
public class rdisMap  implements CommandLineRunner{
	
	@Autowired
	private CompanyCatalogueService companyCatalogueService;
	@Autowired
	private CityService cityService;
	
	public static Map<String, Object> result;
	
	/**单例模式*/
	public static Map<String, Object> result(){
		if(result==null) {
			result=new HashMap<String,Object>();
		}
		return result;
	}
	
	public static Object getResult(String key) {
		return result.get(key);
	}
	
	//定义一个启动加载的类方法(启动完成后自动运行)
	@Override
	public void run(String... args) throws Exception {
		Map<String, Object> map=new HashMap<String, Object>();
		List<CompanyCatalogueEntity> list=companyCatalogueService.queryList(map);
		result();
		result.put("companyCatalogue",list);
		System.out.println("企业目录录入完成!");
		List<CityTree> trees=cityService.geCityTrees();
		result.put("cityTrees",trees);
		System.out.println("city tree 加载完成!");
	}
}

以上就完成了初始状态的类方法调用,map中也存放了部分固定不变又频繁请求的数据。

对于map的调用:

@SuppressWarnings("unchecked")
	@ApiOperation("获取city tree")
	@GetMapping("/tree")
	public R tree() {
		List<CityTree> trees=new ArrayList<CityTree>();
		if(rdisMap.result==null || rdisMap.getResult("cityTrees")!=null) {
			trees=(List<CityTree>) rdisMap.getResult("cityTrees");
		}else {
			trees=cityService.geCityTrees();
		}
		return R.ok().put("cityTrees", trees);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值