public class FaJsonUtils {
private static ObjectMapper om = new ObjectMapper();
public static String objToString(Object obj) {
String result = "";
try {
result = om.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
public static <T> T parseObj(String json, Class<T> clazz) {
T t = null;
if (StringUtils.isNotBlank(json)) {
try {
t = om.readValue(json.getBytes(), clazz);
} catch (IOException e) {
e.printStackTrace();
}
}
return t;
}
}
Redis 对象转字符串 和 字符串转对象辅助工具类
由于formId默认有效时间为7天,所以我们第一次默认时间7天,以后没取一次,设置的缓存时间为有效时间的formId剩余时间,
这里存储formId的方式为 LinkedHashMap 有序的插入。
public class AppletFromIdUtil {
static final String APPLET_MEMBER_FORM_ID_KEY = "APPLET_MEMBER_FORM_ID_KEY_";
static final Integer APPLET_MEMBER_FORM_ID_TIME = 604800; //缓存默认七天
static Map<String,Long> saveOrupdateFormId(String key, String formId) {
Map<String,Long> fromIdMap = FaJsonUtils.parseObj(JedisClient.get(APPLET_MEMBER_FORM_ID_KEY + key), Map.class);
if (fromIdMap != null) {
if (fromIdMap.get(formId) == null) {
fromIdMap.put(formId, System.currentTimeMillis() + APPLET_MEMBER_FORM_ID_TIME * 1000);
JedisClient.set(APPLET_MEMBER_FORM_ID_KEY + key, FaJsonUtils.objToString(fromIdMap),APPLET_MEMBER_FORM_ID_TIME);
}
return fromIdMap;
} else {
Map<String, Long> map = new LinkedHashMap<>();
map.put(formId, System.currentTimeMillis()+APPLET_MEMBER_FORM_ID_TIME * 1000);
JedisClient.set(APPLET_MEMBER_FORM_ID_KEY + "_${_request.memberId}", FaJsonUtils.objToString(map), APPLET_MEMBER_FORM_ID_TIME);
return map;
}
}
static String getMemberFormId(String key) {
Map<String,Long> fromIdMap = FaJsonUtils.parseObj(JedisClient.get(APPLET_MEMBER_FORM_ID_KEY + key), Map.class);
if (fromIdMap != null) {
Iterator<Map.Entry<String, Long>> iterator = fromIdMap.entrySet().iterator();
long nowTime = System.currentTimeMillis();
Map.Entry<String, Long> tailFirst = null;
List<String> removerKey = new ArrayList<>();
for(Map.Entry<String, Long> entry : iterator){
if( entry.getValue() > nowTime){
tailFirst = entry;
break;
}else{
removerKey.add(entry.getKey());
}
}
/**
* 清除过期key
*/
for(String key:removerKey){
fromIdMap.remove(key);
}
Map.Entry<String, Long> tailLast = null;
while (iterator.hasNext()) {
tailLast = iterator.next();
}
if (tailLast == null || (tailFirst != null && tailLast != null && tailFirst.getKey() == tailLast.getKey())) {
JedisClient.del(APPLET_MEMBER_FORM_ID_KEY + key);
} else {
fromIdMap.remove(tailFirst.getKey());
long time = tailLast.getValue();
if (nowTime > time) {
JedisClient.del(APPLET_MEMBER_FORM_ID_KEY + key);
} else {
long cacheTime = time - nowTime;
JedisClient.set(APPLET_MEMBER_FORM_ID_KEY + key, FaJsonUtils.objToString(fromIdMap), (int) cacheTime);
}
}
if (tailFirst != null && tailFirst.getValue() > nowTime) {
return tailFirst.getKey();
}
return null;
} else {
return null;
}
}
注: JedisClient 为获取Redis的工具类,这里不详细的介绍。
这里介绍了后台存储和获取formId的方式。这样可以达到变相的为无限制向用户推送模板消息