Springboot 单例-将数据库的数据缓存在内存中

Springboot 单例-将数据库的数据缓存在内存中

准备配置

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import java.util.Locale;

/**
 * @author Zj 2021/8/11
 */
@Component
public class SpringContextHolder implements BeanFactoryPostProcessor, ApplicationContextAware {

	/** 日志记录器 */
	private static final Logger LOGGER = LoggerFactory.getLogger(SpringContextHolder.class);

	/** ApplicationContext */
	private static ApplicationContext context;

	/** ServletContext */
	private static ServletContext servletContext;

	/** Environment */
	private static Environment environment;

	/** MessageSourceAccessor */
	private static MessageSourceAccessor messages;

	/**
	 * Constructor<br>
	 * 私有化工具类的构造函数
	 */
	private SpringContextHolder() {
	}

	/**
	 * get ApplicationContext<br>
	 *
	 * @return ApplicationContext
	 */
	public static ApplicationContext getSpringContext() {

		return context;
	}


	public static ApplicationContext get() {

		return context;
	}

	/**
	 * get {@link ServletContext}<br>
	 *
	 * @return {@link ServletContext}
	 */
	public static ServletContext getServletContext() {

		return servletContext;
	}

	/**
	 * get Environment<br/>
	 *
	 * @return
	 */
	public static Environment getEnvironment() {

		return environment;
	}

	/**
	 * 根据名字获得spring context中的bean<br>
	 *
	 * @param name bean的名称
	 * @return bean
	 */
	public static Object getBean(String name) {

		return context.getBean(name);
	}

	/**
	 * 根据类型获得spring context中的bean<br>
	 *
	 * @param requiredType bean的类型
	 * @return bean
	 */
	public static <T> T getBean(Class<T> requiredType) {

		return context.getBean(requiredType);
	}

	/**
	 * 根据名称和类型获得spring context中的bean<br>
	 *
	 * @param name         bean 的名称
	 * @param requiredType bean的类型
	 * @return bean
	 */
	public static <T> T getBean(String name, Class<T> requiredType) {

		return context.getBean(name, requiredType);
	}

	/**
	 * 获取properties的值,没有获取到返回null<br>
	 *
	 * @return 该key对应的value值
	 */
	public static String getProperty(String key) {

		return environment.getProperty(key);
	}

	/**
	 * 获取properties的值,没有获取到抛出异常<br>
	 *
	 * @throws IllegalStateException if the key cannot be resolved
	 * @return 该key对应的value值
	 */
	public static String getRequiredProperty(String key) {

		return environment.getRequiredProperty(key);
	}

	/**
	 * set Servlet Context<br>
	 *
	 * @param sc ServletContext
	 */
	public static void setServletContext(ServletContext sc) {

		servletContext = sc;
	}

	/**
	 * 获取国际化访问工具<br>
	 *
	 * @return 国际化访问工具
	 */
	public static MessageSourceAccessor getMessageSourceAccessor() {

		return messages;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {

		init(applicationContext);
	}

	/**
	 * 对相关的属性进行赋值<br/>
	 *
	 * @param applicationContext ApplicationContext
	 */
	private static void init(ApplicationContext applicationContext) {

		context = applicationContext;
		environment = context.getEnvironment();

		if (context instanceof WebApplicationContext) {

			servletContext = ((WebApplicationContext) context).getServletContext();
		}

		messages = new MessageSourceAccessor(context, Locale.SIMPLIFIED_CHINESE);
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {

		LOGGER.info("Spring context holder initialized successful");
	}
}

单例实现

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hico.projects.yige.moapi.visitor.resp.Respondent;
import com.hico.projects.yige.mocallback.web.SpringContextHolder;
import com.hico.projects.yige.service.guest.GuestService;

import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 被访人信息缓存工具
 * <p>
 * 将魔点的被访人支持访问的列表
 * </p>
 *
 * @author Zj 2021/9/11
 */
public class RespondentCacheUtil {

	private static RespondentCacheUtil INSTANCE;

	/**
	 * 被访人列表
	 */
	private List<Respondent> respondentList = new ArrayList<>();

	/**
	 * 被访人 分组 by id
	 */
	private Map<Long, Respondent> respondentMapByPersonId = new HashMap<>();

	/**
	 * 被访人 分组 by 手机号
	 */
	private Map<String, Respondent> respondentMapByMobile = new HashMap<>();

	/**
	 * 同步时间戳
	 */
	private long synchTime = 0L;

	/**
	 * 过期时效 30 分钟
	 */
	private static final long EXPIRES_TIME = 1800000L;

	public static RespondentCacheUtil getInstance() {
		if (ObjectUtil.isNull(INSTANCE)) {
			INSTANCE = new RespondentCacheUtil();
			INSTANCE.synchTime = Instant.now().toEpochMilli();
		}
		return INSTANCE;
	}

	private RespondentCacheUtil() {
		init();
	}

	public void init() {
		synchRespondentList();
	}

	/**
	 * 同步人员信息列表
	 */
	public void synchRespondentList() {
		GuestService guestService = SpringContextHolder.getBean(GuestService.class);

		// 从数据源获取所需要的数据
		this.respondentList = guestService.getRespondentList();

		this.respondentMapByPersonId =
			this.respondentList.stream()
				.collect(Collectors.toMap(Respondent::getPersonId, Function.identity()));

		this.respondentMapByMobile =
			this.respondentList.stream()
				.filter(member -> StrUtil.isNotBlank(member.getMobile()))
				.collect(Collectors.toMap(Respondent::getMobile, Function.identity()));

		this.synchTime = Instant.now().toEpochMilli();
	}

	/**
	 * 更新人员列表信息
	 */
	public void updateRespondentList() {
		long nowTime = Instant.now().toEpochMilli();
		if ((nowTime - this.synchTime) > EXPIRES_TIME) {
			this.synchRespondentList();
		}
	}

	/**
	 * 通过手机号获取用户
	 * <p>
	 *     如果没有的话重新拉
	 * </p>
	 */
	public Respondent getRespondentInfoByMobile(String mobile) {
		this.updateRespondentList();
		Respondent respondent = this.respondentMapByMobile.get(mobile);
		if (ObjectUtil.isNull(respondent)) {
			this.synchRespondentList();
			respondent = this.respondentMapByMobile.get(mobile);
		}
		return respondent;
	}

	/**
	 * 通过id获取用户信息
	 * <p>
	 * 	 如果没有的话重新拉一遍
	 * </p>
	 */
	public Respondent getRespondentInfoByMoId(Long moId) {
		this.updateRespondentList();
		Respondent respondent = this.respondentMapByPersonId.get(moId);
		if (ObjectUtil.isNull(respondent)) {
			this.synchRespondentList();
			respondent = this.respondentMapByPersonId.get(moId);
		}
		return respondent;
	}

	public List<Respondent> getRespondentList() {
		this.updateRespondentList();
		if (CollectionUtil.isEmpty(this.respondentList)) {
			this.synchRespondentList();
		}
		return this.respondentList;
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值