엔드 시스템이 많고 가끔씩 또는 몇 개의 엔드 시스템과 각각의 메시지에 자주 메시지를 보내야하는지 약간 무게가 나가야합니다.
엔드 시스템이 많은 경우 말 그대로 엔드 시스템 당 하나의 스레드를 사용하는 것이 실제로 모든 컴퓨터에 지속적으로 메시지를 스트리밍하지 않는 한 정상보다 약간 소리가납니다. 특정 경계 사이에서만 성장할 수있는 스레드 풀을 제안 할 것입니다. 이렇게하려면 ThreadPoolExecutor를 사용할 수 있습니다. 당신은 몇 가지 끝 기계가있는 경우, 당신은 기계마다의 BlockingQueue을 가질 수
Executor msgExec = new ThreadPoolExecutor(...);
public void sendMessage(final String machineId, byte[] message) {
msgExec.execute(new Runnable() {
public void run() {
sendMessageNow(machineId, message);
}
});
}
private void sendMessageNow(String machineId, byte[] message) {
// open connection to machine and send message, thinking
// about the case of two simultaneous messages to a machine,
// and whether you want to cache connections.
}
및 스레드 : 당신이 메시지를 게시 할 필요가있을 때, 당신은 실제로 메시지를 보내드립니다 집행자에 실행 가능한 제출 다음 메시지를 기다리는 블로킹 대기열 당. 이 경우, 패턴은 (테스트되지 않은 오프 최고 수준의 머리 일요일 아침 코드를 조심) 다음과 같다 :
이 경우
ConcurrentHashMap<String,BockingQueue> queuePerMachine;
public void sendMessage(String machineId, byte[] message) {
BockingQueue<Message> q = queuePerMachine.get(machineId);
if (q == null) {
q = new BockingQueue<Message>();
BockingQueue<Message> prev = queuePerMachine.putIfAbsent(machineId, q);
if (prev != null) {
q = prev;
} else {
(new QueueProessor(q)).start();
}
}
q.put(new Message(message));
}
private class QueueProessor extends Thread {
private final BockingQueue<Message> q;
QueueProessor(BockingQueue<Message> q) {
this.q = q;
}
public void run() {
Socket s = null;
for (;;) {
boolean needTimeOut = (s != null);
Message m = needTimeOut ?
q.poll(60000, TimeUnit.MILLISECOND) :
q.take();
if (m == null) {
if (s != null)
// close s and null
} else {
if (s == null) {
// open s
}
// send message down s
}
}
// add appropriate error handling and finally
}
}
해당 시스템에 대한 메시지를 60 초 내에 도착하지 않는 경우, 우리는 연결을 닫습니다 .
대신 JMS를 사용해야합니까? 글쎄, 당신은이 소리가 당신에게 복잡하게 들리는 지 짐작해야합니다. 내 개인적 감각은 특수한 틀을 정당화하는 것은 충분히 복잡하지 않다는 것입니다. 그러나 의견이 다를 것이라고 확신합니다.
P. 현실에서는 이제 이것을 보았습니다. 아마도 스레드 객체 내에 큐를 놓고 컴퓨터 ID -> 스레드 객체를 매핑하는 것입니다. 어쨌든, 당신은 아이디어를 얻습니다.