Springboot项目启动时将数据缓存map中

Springboot项目启动时将数据缓存map中,测试通过

注意点

注意项目启动时容器对象还未初始化完成,不能用 @Autowired注入

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Component
public class CodeCache {
   
    public static Map<String, String> map = new HashMap<String, String>();

    private static Logger logger = LoggerFactory.getLogger(CodeCache.class);
 
    private static CityDao cityDao;
 
 //不能用 @Autowired注入 此处手动注入对象
    public WxUtil(CityDao cityDao) {
        this.cityDao= cityDao;
    }
 
 
    @PostConstruct//优先执行
    public static  void init() {
       
        List<Properties> list= cityDao.selectCodeALL();
        for (Properties prop: list) {
            map.put(code.getKey(),code.getValue());
        }
        logger.info("map======"+map )
    }
 
    @PreDestroy
    public void destroy() {
        //系统运行结束
    }
  
    public static String getValue(String key) {
        return map.get(key);
    }
    //@Scheduled(cron = "0 0 0/2 * * ?")//每2小时执行一次缓存
  //  public void testOne() {init();}
 
}

调用CodeCache .getValue(“key”)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot项目启动时数据数据缓存Map,可以使用Spring Boot提供的ApplicationRunner或CommandLineRunner接口,在项目启动完成后执行指定的逻辑。 具体实现步骤如下: 1. 创建一个缓存类,用于缓存数据数据: ```java @Component public class DataCache { private Map<Long, Object> cache = new HashMap<>(); public void put(Long id, Object data) { cache.put(id, data); } public Object get(Long id) { return cache.get(id); } public Map<Long, Object> getAll() { return Collections.unmodifiableMap(cache); } } ``` 2. 创建一个数据加载类,实现ApplicationRunner或CommandLineRunner接口,并在其实现的run方法数据数据缓存Map: ```java @Component public class DataLoadRunner implements ApplicationRunner { @Autowired private DataCache dataCache; @Autowired private DataSource dataSource; @Override public void run(ApplicationArguments args) throws Exception { try (Connection conn = dataSource.getConnection()) { String sql = "SELECT id, data FROM table"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { Long id = rs.getLong("id"); Object data = rs.getObject("data"); dataCache.put(id, data); } } } } } ``` 在这个例子,我们使用了Spring Boot提供的DataSource来获取数据库连接,然后使用JDBC API将数据数据查询出来,并存储至DataCache。 3. 在Spring Boot启动类添加注解@EnableScheduling,开启定时任务功能,以便在数据发生变化时,能够及时更新缓存。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,在Spring Boot项目启动完成后,数据缓存Map,并可以通过DataCache在整个应用程序访问。如果数据发生变化,可以通过定时任务重新加载数据缓存

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值