均衡算法代码(java)(2)

来源:互联网 发布:淘宝刷砖平台 编辑:程序博客网 时间:2024/06/10 06:38

具体实现

///日期:2011-09-23///描述:发送数据对象public class InputValueItem implements IValueItem {public Socket SocketItem;private boolean m_IsRead;private Object m_obj;private HashMap<String, String> m_config;private String m_msg;public InputValueItem(Socket socket) {SocketItem = socket;m_IsRead = false;}public HashMap<String, String> GetConfig() {return m_config;}public void SetConfig(HashMap<String, String> config) {m_config = config;}public void SetInputValue(Object obj) {m_obj = obj;m_IsRead = true;}public Object GetInputValue() {return m_obj;}public boolean IsBind() {return m_IsRead;}public void SetMessage(String msg) {m_msg = msg;}public void Finally() throws Exception {if (null != SocketItem && !SocketItem.isClosed()) {SocketItem.close();}}private byte[] intTobyteArray(int i) {return new byte[] { (byte) ((i >> 24) & 0xFF),(byte) ((i >> 16) & 0xFF), (byte) ((i >> 8) & 0xFF),(byte) (i & 0xFF) };}}
///日期:2011-09-23///描述:服务容器@SuppressWarnings("serial")public class ServiceContainer extends ThreadPoolCollect {private List<HashMap<String, String>> m_Config;public ServiceContainer() throws Exception {bindConfig();bindService();}public ServiceContainer(IThreadLog log) throws Exception {SetMessage(log);bindConfig();bindService();}@Overridepublic IThreadNode CreateThreadNode() {ThreadNode node = new ThreadNode(3) {public void ThreadCallback(Object obj) throws Exception {//这里写你接到请求后处理的东西}};node.SetMessage(GetMessage());return node;}private void bindConfig() throws Exception {File dir = new File("ServiceContainer"); //从ServiceContainer目录下获取服务器信息配置文件File[] fileList = dir.listFiles();m_Config = new ArrayList<HashMap<String, String>>();for (int i = 0; i < fileList.length; i++) {HashMap<String, String> hash = new HashMap<String, String>();m_Config.add(hash);DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document doc = builder.parse(fileList[i]);NodeList nodeList = doc.getElementsByTagName("ITEM");for (int iNode = 0; iNode < nodeList.getLength(); iNode++) {Element node = (Element) nodeList.item(iNode);hash.put(node.getAttribute("NAME").toUpperCase(), node.getTextContent());}}}private void bindService() {for (HashMap<String, String> item : m_Config) {IThreadPool pool = new ThreadPool(item);pool.SetMessage(GetMessage());pool.SetParent(this);add(pool);}}}
///日期:2011-09-23///描述:均衡类线程对象public class ThreadNode extends Thread implements IThreadNode {private int m_Current, m_Max, m_Err, m_CurrentErr;private ThreadStatic m_ThreadStatic;private IValueItem m_Parameter;private String m_Name;private IThreadPool m_parent;private IThreadLog m_Message;private boolean m_IsStart;private HashMap<String, String> m_Config;public ThreadNode(IThreadPool parent, int max) {m_IsStart = false;m_CurrentErr = 0;m_Err = 3;m_Current = max;m_Max = max;m_ThreadStatic = ThreadStatic.NONE;m_Name = Parent().GetName() + "_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ (int) (Math.random() * 10000);super.setName(m_Name);}public ThreadNode(int max) {m_IsStart = false;m_Current = max;m_CurrentErr = 0;m_Err = 3;m_Max = max;m_ThreadStatic = ThreadStatic.NONE;}public void run() {GetMessage().ShowMessage("开始调用回调");try {m_ThreadStatic = ThreadStatic.START;m_IsStart = true;ThreadCallback(GetParameter());itemFinally();m_ThreadStatic = ThreadStatic.END;} catch (Exception e) {m_CurrentErr++;Parent().SetError();GetMessage().ShowAndWriteLog("发送时发生错误:" + e.getMessage());returnPool();}GetMessage().ShowMessage("结束调用回调");}private void itemFinally() {try {GetParameter().Finally();} catch (Exception e) {GetMessage().ShowAndWriteLog("发生错误:" + e.getMessage());}}public boolean IsOver() {return ThreadStatic.END == m_ThreadStatic;}public void ThreadCallback(Object obj) throws Exception {// TODO Auto-generated method stub}public void Execute() {if (ThreadStatic.START == GetThreadStatic() && !m_IsStart)start();else if (ThreadStatic.WAIT == GetThreadStatic() && m_Current > 0)m_Current--;}public int GetCurrent() {return m_Current;}public boolean IsImmediate() {return GetCurrent() <= 0;}public int GetMax() {return m_Max;}public void Reset() {m_Current = m_Max;m_ThreadStatic = ThreadStatic.NONE;m_Parameter = null;}public ThreadStatic GetThreadStatic() {return m_ThreadStatic;}public void SetThreadStatic(ThreadStatic threadStatic) {m_ThreadStatic = threadStatic;}public void SetParameter(IValueItem obj) {m_Parameter = obj;}public IValueItem GetParameter() {return m_Parameter;}public String GetName() {return m_Name;}public IThreadPool Parent() {return m_parent;}public void SetParent(IThreadPool parent) {m_parent = parent;setThreadName();SetConfig(m_parent.Config());}public IThreadLog GetMessage() {return m_Message;}public void SetMessage(IThreadLog msg) {m_Message = msg;}public HashMap<String, String> Config() {return m_Config;}public void SetConfig(HashMap<String, String> cfg) {m_Config = cfg;bindConfig();if (null != m_Parameter)m_Parameter.SetConfig(m_Config);}public void SetErrorCount(int error) {m_CurrentErr = error;}public int GetErrorCount() {return m_CurrentErr;}private void bindConfig() {m_IsStart = false;m_Err = Integer.parseInt(Config().get("ERR"));m_Max = Integer.parseInt(Config().get("WAIT"));m_Current = m_Max;m_ThreadStatic = ThreadStatic.NONE;}private void setThreadName() {StringBuffer sb = new StringBuffer();sb.append(Parent().GetName());sb.append("_");sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));sb.append((int) (Math.random() * 10000));m_Name = sb.toString();super.setName(m_Name);}private void returnPool() {m_IsStart = false;m_ThreadStatic = ThreadStatic.END;if (isErrNext()) {Parent().ReturnPool(this);} else {GetMessage().ShowAndWriteLog("错误次数超过最大值");itemFinally();}}private boolean isErrNext() {return m_CurrentErr < m_Err;}}
///日期:2011-09-23///描述:线程池public class ThreadPool implements IThreadPool {private List<IThreadNode> m_ThreadNodeCollect;private String m_Name;private int m_Current, m_Max, m_MaxExecute;private HashMap<String, String> m_Config;private IThreadLog m_Message;private ThreadPoolCollect m_collect;public ThreadPool(HashMap<String, String> config) {SetConfig(config);m_Name = Config().get("NAME");m_Max = Integer.parseInt(Config().get("MAX"));m_Current = 0;m_MaxExecute = Integer.parseInt(Config().get("EXEC"));m_ThreadNodeCollect = new ArrayList<IThreadNode>();}public IThreadNode GetThreadNode(int index) {return GetThreadNodeCollect().get(index);}public IThreadNode GetThreadNode(String name) {for (IThreadNode node : GetThreadNodeCollect()) {if (name == node.GetName()) {return node;}}return null;}public List<IThreadNode> GetThreadNodeCollect() {return m_ThreadNodeCollect;}public int GetCurrent() {return m_Current;}public int GetMax() {return m_Max;}public String GetName() {return m_Name;}public void Add(IThreadNode node) {GetMessage().ShowMessage("在 " + GetName() + " 上创建了一个线程");m_Current++;m_ThreadNodeCollect.add(node);node.SetParent(this);node.SetThreadStatic(ThreadStatic.START);GetMessage().ShowMessage("开始执行线程");node.Execute();}public boolean IsMax() {return m_Current >= GetMax();}public boolean IsBusy() {// if (!(m_ThreadNodeCollect.size() < m_MaxExecute))clear();return !(m_ThreadNodeCollect.size() < m_MaxExecute);}public HashMap<String, String> Config() {return m_Config;}public void SetConfig(HashMap<String, String> cfg) {m_Config = cfg;}public IThreadLog GetMessage() {return m_Message;}public void SetMessage(IThreadLog msg) {m_Message = msg;}public void SetParent(ThreadPoolCollect parent) {m_collect = parent;}public void ReturnPool(IThreadNode node) {m_collect.ReturnPool(node);}public void Reset() {m_Current = 0;}public void SetError() {m_Current = GetMax();}private void clear() {for (int i = m_ThreadNodeCollect.size() - 1; i >= 0; i--) {if (ThreadStatic.END == m_ThreadNodeCollect.get(i).GetThreadStatic()) {m_ThreadNodeCollect.remove(i);}}}}
///日期:2011-09-23///描述:线程池集合用来分配个池执行状态@SuppressWarnings("serial")public class ThreadPoolCollect extends ArrayList<IThreadPool> {private Queue<IThreadNode> m_dataList;private ExecThread m_Exec;private boolean m_Start, m_isout;private int m_PoolIndex;private ThreadPoolCollect m_instance;private IThreadLog m_msg;public ThreadPoolCollect() {m_dataList = new LinkedList<IThreadNode>();m_Exec = new ExecThread();m_Start = false;m_isout = false;m_PoolIndex = 0;m_instance = this;}public void AddItem(IValueItem item) {IThreadNode thread = CreateThreadNode();thread.SetParameter(item);m_dataList.add(thread);}public void ReturnPool(IThreadNode thread) {IThreadNode node = CreateThreadNode(thread.GetParameter());node.SetErrorCount(thread.GetErrorCount());((LinkedList<IThreadNode>) m_dataList).addFirst(node);}public void Start() {if (!IsStart()) {m_isout = false;m_Start = true;m_Exec.start();}}public boolean IsOut() {return m_isout;}public boolean IsStart() {return m_Start;}public void Close() {m_Start = false;}public void NextPool() {m_PoolIndex++;if (!(m_PoolIndex < this.size()))m_PoolIndex = 0;}public void SetMessage(IThreadLog msg) {m_msg = msg;}public IThreadLog GetMessage() {return m_msg;}public IThreadNode CreateThreadNode() {// TODO Auto-generated method stubreturn null;}public IThreadNode CreateThreadNode(IValueItem obj) {IThreadNode node = CreateThreadNode();node.SetMessage(m_msg);node.SetParameter(obj);return node;}class ExecThread extends Thread {public void run() {while (m_Start) {execImmediate();IThreadPool pool = get(m_PoolIndex);if (pool.IsMax()) {pool.Reset();NextPool();} else if (!pool.IsBusy() && m_dataList.size() > 0) {pool.Add(m_dataList.poll());}for (IThreadNode node : m_dataList)node.Execute();try {Thread.sleep(1000);} catch (InterruptedException e) {m_Start = false;}}m_isout = true;m_Start = false;GetMessage().ShowAndWriteLog("线程被退出");}private void execImmediate() {for (IThreadPool node : m_instance) {if (!(m_dataList.size() > 0))return;while (!node.IsMax() && !node.IsBusy() && m_dataList.size() > 0) {if (m_dataList.element().IsImmediate())node.Add(m_dataList.poll());elsereturn;}}}}}
///日期:2011-09-23///描述:线程状态枚举public enum ThreadStatic {NONE(0), START(1), END(2), WAIT(3);private final int value;ThreadStatic(int value) {this.value = value;}public int value() {return value;}}