package com.qianwen.smartman.common.provider; import cn.hutool.cache.impl.TimedCache; import cn.hutool.core.util.RandomUtil; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import com.qianwen.smartman.common.cache.I18nCache; import com.qianwen.smartman.common.constant.I18nRedisKeyConstant; import com.qianwen.core.i18n.dto.I18nMessage; import com.qianwen.core.i18n.listener.AbstractMessageEventListener; import com.qianwen.core.i18n.provider.I18nMessageProvider; import com.qianwen.smartman.modules.system.dto.I18nDataUnique; import com.qianwen.smartman.modules.system.entity.I18nData; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.Topic; import org.springframework.stereotype.Component; @Component public class CustomI18nMessageProvider extends AbstractMessageEventListener implements I18nMessageProvider { private static final int MILLISECONDS_OF_HOUR = 3600000; private static final int MIN_TIMEOUT = 3240000; private static final int MAX_TIMEOUT = 3960000; private final TimedCache cache = new TimedCache<>(MILLISECONDS_OF_HOUR, new ConcurrentHashMap<>()); public CustomI18nMessageProvider() { this.cache.schedulePrune(1000L); } public I18nMessage getI18nMessage(String code, Locale locale) { I18nData i18nData; String languageTag = locale.toLanguageTag(); String cacheKey = getCacheKey(code, languageTag); I18nMessage i18nMessage = (I18nMessage) this.cache.get(cacheKey); if (i18nMessage == null && (i18nData = I18nCache.getByCodeAndLanguageTag(code, languageTag)) != null) { i18nMessage = converterToI18nMessage(i18nData); int timeout = RandomUtil.randomInt((int) MIN_TIMEOUT, (int) MAX_TIMEOUT); this.cache.put(cacheKey, i18nMessage, timeout); } return i18nMessage; } private String getCacheKey(String code, String languageTag) { return code + ":" + languageTag; } private I18nMessage converterToI18nMessage(I18nData i18nData) { I18nMessage i18nMessage = new I18nMessage(); i18nMessage.setMessage(i18nData.getMessage()); i18nMessage.setCode(i18nData.getCode()); i18nMessage.setLanguageTag(i18nData.getLanguageTag()); return i18nMessage; } protected void handleMessage(I18nDataUnique i18nDataUnique) { String cacheKey = getCacheKey(i18nDataUnique.getCode(), i18nDataUnique.getLanguageTag()); this.cache.remove(cacheKey); } public Topic topic() { return new ChannelTopic(I18nRedisKeyConstant.CHANNEL_I18N_DATA_UPDATED); } }