启动加载缓存

1.web.xml引入

  <servlet>
    <servlet-name>InitServlet</servlet-name>
    <servlet-class>com.hxy.sys.servelt.InitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

 

2.InitServlet类

 

import com.hxy.base.utils.SpringContextUtils;
import com.hxy.sys.dao.CodeDao;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类的功能描述.
 * 继承HttpServlet,重写Init方法,实现加载servlet时,做一些操作
 */
public class InitServlet extends HttpServlet{
    private static CodeDao codeDao = SpringContextUtils.getBean(CodeDao.class);
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

ApplicationContext context1 = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
SystemApi aaabbbb = context1.getBean(SystemApi.class);


 String webRoot = config.getServletContext().getContextPath(); config.getServletContext().setAttribute("webRoot", webRoot);//Web根目录 config.getServletContext().setAttribute("resRoot", webRoot+"/statics");//资态资源根目录 //缓存全部数据字典 CodeCache(); } /** * 缓存全部数据字典 */ public void CodeCache(){ ........................ }}

 

3.工具类

 

import org.apache.commons.lang3.Validate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 类SpringContextUtils的功能描述:
 * Spring Context 工具类
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
	public static ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)   throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}
	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}
	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}
	/**
	 * 检查ApplicationContext不为空.
	 */
	private static void assertContextInjected() {
		Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
	}
	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}
	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}
	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}
	public static Class<? extends Object> getType(String name) {
		return applicationContext.getType(name);
	}
}

4.

加载SpringContextUtils到容器
    <bean class="com.bbbb.aaa.base.utils.SpringContextUtil" lazy-init="false"/>

 

 

 

### 加载数据到缓存的最佳实践 在Spring应用程序中,为了提高性能并减少数据库查询次数,通常会在应用启动时将常用的数据加载到内存中的缓存。以下是实现这一目标的一些最佳实践: #### 使用`CommandLineRunner`或`ApplicationListener` 可以通过实现 `CommandLineRunner` 接口或者监听 `ApplicationReadyEvent` 来执行初始化逻辑。这两种方式都可以确保在Spring容器完全初始化之后运行自定义代码。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class CacheLoader implements CommandLineRunner { private final MyService myService; public CacheLoader(MyService myService) { this.myService = myService; } @Override public void run(String... args) throws Exception { // 调用服务方法来填充缓存 myService.loadCache(); } } ``` 上述代码通过调用 `myService.loadCache()` 方法,在应用启动时触发缓存预热操作[^1]。 #### 配置缓存管理器 Spring Boot 提供了自动配置的缓存支持,默认情况下可以使用基于ConcurrentHashMap的简单缓存。如果需要更高级的功能(如过期时间、持久化),可以选择集成其他缓存提供者(例如 Ehcache 或 Redis)。可以在 `application.properties` 中指定缓存类型: ```properties spring.cache.type=redis ``` 对于Redis缓存的支持,需引入相应的依赖项,并确保服务器已正确安装和配置[^3]。 #### 缓存注解的应用 利用Spring框架内置的缓存注解简化开发流程。例如,标记某个方法的结果会被存储至特定名称的空间下以便后续重复访问无需重新计算。 ```java @Service public class MyService { @Cacheable(value = "items", key = "#id") public Item findById(Long id){ return repository.findById(id).orElse(null); } public void loadCache(){ List<Item> items = repository.findAll(); items.forEach(item -> findById(item.getId())); } } ``` 这里展示了如何结合 `@Cacheable` 注解与业务逻辑完成批量加载的任务[^2]。 #### 性能考量与其他建议 - **异步加载**:考虑采用多线程技术进行后台处理以免阻塞主线程。 - **监控健康状态**:定期检查缓存命中率以及大小调整策略是否合理有效。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值