Как написать минималистичный Java-клиент для OpenMQ
Помогите MQ nubee написать свой первый Java-клиент, я немного заблудился в документации Oracle. У меня OpenMQ запущен и работает. В Консоли администрирования OpenMQ я установил посредник с именем "MyFirstTest", один из 6 сервисов - это "jms" (который, кажется, является наиболее простым в использовании сервисом), этот сервис тоже работает и работает (говоря: состояние сервиса работает). Итак, я подхожу к интересной части. Как мне подключиться к брокеру "MyFirstTest", чтобы потом отправить сообщение, и, наконец, хотя бы меньше всего прочитать это сообщение, возможно, от второго клиента.
Я думаю, что мне нужно найти уже существующую очередь вместо использования новой com.sun.messaging.Queue
Любой пример или ссылка на приветствуется.
public class HelloWorldMessage {
public static void main(String[] args) {
try {
ConnectionFactory myConnFactory;
Queue myQueue;
myConnFactory = new com.sun.messaging.ConnectionFactory();
Connection myConn = myConnFactory.createConnection();
Session mySess = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
myQueue = new com.sun.messaging.Queue("MyFirstTest");
//Create a message producer.
MessageProducer myMsgProducer = mySess.createProducer(myQueue);
//Create and send a message to the queue.
TextMessage myTextMsg = mySess.createTextMessage();
myTextMsg.setText("Hello World");
System.out.println("Sending Message: " + myTextMsg.getText());
myMsgProducer.send(myTextMsg);
//Create a message consumer.
MessageConsumer myMsgConsumer = mySess.createConsumer(myQueue);
//Start the Connection created in step 3.
myConn.start();
//Receive a message from the queue.
Message msg = myMsgConsumer.receive();
//Retreive the contents of the message.
if (msg instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) msg;
System.out.println("Read Message: " + txtMsg.getText());
}
//Close the session and connection resources.
mySess.close();
myConn.close();
} catch (Exception jmse) {
System.out.println("Exception occurred : " + jmse.toString());
jmse.printStackTrace();
}
}
}
1 ответ
//Assuming server supports multiple clients, your client can look like this:
//Ref: http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
//untested code
class client{
.....
....
private static Socket echoSocket;
//main can be in another class also
public static void main(.... args[]){
client nodeI,nodeII;
nodeI = new client("speaker/sender");
nodeII = new client("listener/recvr");
nodeI.connect2Server();
nodeI.sendMssgInstr2Server(node);
}
public void connect2Server(){
try {
echoSocket = new Socket("<jms.srvr.ip>", <port#>);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: <jms.srvr.ip>.");
System.exit(1);
}
}
public void sendMssgInstr2Server throws IOException (client RecipientClientNodeII){
out = new PrintWriter(echoSocket.getOutputStream(), true);
out.println("sending message:"+mssgQueue.poll() + " =>recipient client is now reading:"+RecipientClientNodeII.receive);
}
public void receive(){
try{
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (IOException e) {
System.err.println("Couldn't get I/O for "+"the connection to: <jms.srvr.ip>.");
System.exit(1);
}
while(1)
in.readLine();
}
//other methods
.......
.......
}; //class client ends