利用Resource接口获取缓存数据
package com.example.emaildemo.cache;
import java.util.stream.Stream;
/**
* 资源接口
* 资源类
* @param <T>
*/
public interface Resource<T> {
/**
* 资源加载并缓存
*/
void init();
/**
* 获取
* @param key
* @return
*/
T get(String key);
/**
* 是否存在
* @param key
* @return
*/
boolean contains(String key);
/**
* 返回资源
* @return
*/
Stream<T> stream();
/**
* 刷新资源
*/
void refresh();
}
实现类
package com.example.emaildemo.cache;
import com.example.emaildemo.cache.resource.RuleResource;
import com.example.emaildemo.utils.SpringContextHolder;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
@Component
public class RuleCacheResource implements Resource<RuleResource> {
private static Map<String,RuleResource> cacheMap = new ConcurrentHashMap<>();
@Override
public void init() {
Map<String,RuleResource> ruleResourceMap = SpringContextHolder.getApplicationContext().getBeansOfType(RuleResource.class);
cacheMap.putAll(ruleResourceMap);
}
@Override
public RuleResource get(String key) {
return cacheMap.get(key);
}
@Override
public boolean contains(String key) {
return cacheMap.containsKey(key);
}
@Override
public Stream<RuleResource> stream() {
return cacheMap.values().stream();
}
@Override
public void refresh() {
cacheMap.clear();
}
}
package com.example.emaildemo.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Objects;
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext(){
Objects.requireNonNull(context);
return context;
}
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
}