package com.zy.core.cache; import com.zy.core.ThreadHandler; import com.zy.core.enums.SlaveType; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 线程缓存容器 * Created by vincent on 2020/8/4 */ public class SlaveConnection { private static final String _LINK = "_"; private static final Map conContain = new ConcurrentHashMap<>(); public static void put(SlaveType type, Integer id, ThreadHandler threadHandler) { String key = toKey(type, id); remove(type, id); conContain.put(key, threadHandler); } public static ThreadHandler get(SlaveType type, Integer id) { return conContain.get(toKey(type, id)); } public static void remove(SlaveType type, Integer id) { ThreadHandler threadHandler = get(type, id); if (null == threadHandler) { return; } conContain.remove(toKey(type, id)); threadHandler.close(); } public static Integer remove(ThreadHandler threadHandler) { if (null == threadHandler) { return null; } String key = null; for (Map.Entry entry : conContain.entrySet()) { if (entry.getValue() == threadHandler) { key = entry.getKey(); break; } } if (null != key) { SlaveType type = SlaveType.findInstance(key); Integer id = Integer.parseInt(key.split(_LINK)[1]); remove(type, id); return id; } else { return null; } } private static String toKey(SlaveType type, Integer id) { return type.toString() + _LINK + id; } }