Monday, September 26, 2005

ทดลอง send message จาก ruby ไป java ผ่าน Stomp Protocol

วันนี้ทดลองใช้ ActiveMQ เป็นตัวกลางในการ communicate
ระหว่าง Java กับ Ruby

ในส่วนของ Java ผมใช้ jencks ซึ่งเป็น lightweight container
ที่สามารถ deploy ใน Spring ได้ ตัว jencks ทำให้เรา run
Message Bean นอก j2ee server ได้

ตัว Message Bean ทดลองเขียนดังนี้
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class EchoBean implements MessageListener {

public void onMessage(Message msg) {
try {
System.out.println("i got message");
TextMessage txt = (TextMessage) msg;
System.out.println(txt.getText());
} catch (JMSException je) {
je.printStackTrace();
}
}
}


ส่วนของ Spring Application Config file นี้ยุ่งขึ้นมาหน่อย
เขียนดังนี้

เริ่มด้วยการ add jencks ก่อน
<bean id="jencks" class="org.jencks.JCAContainer">
<property name="bootstrapContext">
<bean class="org.jencks.factory.BootstrapContextFactoryBean">
<property name="threadPoolSize" value="25"/>
</bean>
</property>

<property name="resourceAdapter">
<bean id="activeMQResourceAdapter" class="org.activemq.ra.ActiveMQResour
ceAdapter">
<property name="serverUrl" value="tcp://localhost:61616"/>
</bean>
</property>
</bean>


จากนั้นก็ใส่ EchoBean ที่เราเขียนเข้าไป
<bean id="monitor" factory-method="addConnector" factory-bean="jencks" singleton
="true">
<property name="activationSpec">
<bean class="org.activemq.ra.ActiveMQActivationSpec">
<property name="destination" value="Monitor.Queue"/>
<property name="destinationType" value="javax.jms.Queue"/>
</bean>
</property>

<property name="ref" value="echoBean"/>
</bean>

<bean id="echoBean" class="mx.test.mq.EchoBean" singleton="true"/>


เท่านี้ก็เรียบร้อย เวลา run ก็เพียงแต่ load Application Context
ClassPathXmlApplicationContext appContext = 
new ClassPathXmlApplicationContext(
new String[] {"beans.xml"});


ก่อนที่จะเขียนส่วน Ruby Client
เราต้อง config ActiveMQ ให้เปิด port ที่รับ Stomp protocol เสียก่อน
ซึ่งทำได้โดย เข้าไปแก้ activemq.xml
เพิ่มบรรทัดนี้เข้าไป
<connector>
<serverTransport uri="stomp://localhost:61626"/>
</connector>


ทีนี้มาว่าด้วยส่วน ruby บ้าง
ตัว api ที่ใช้ interface กับ Stomp สามารถ download ได้ที่นี่ Link
วิธีการใช้งานทำได้ดังนี้

เริ่มต้นด้วยการ open connection กับ ActiveMQ ก่อน
conn = Stomp::Connection.open('user','pass','localh',port)


ในกรณีที่ต้องการส่ง Message ก็เพียงแต่
conn.send('/queue/test', 'hello');

Note: เราต้องระบุชนิดของ destination เสมอ
โดยการระบุ prefix ที่จะต้องขึ้นต้นด้วย /queue/ หรือ /topic/


กรณีที่ต้องการส่งหลายๆ message และให้มี transaction control ด้วย
ก็เพียงแต่ใส่ begin, commit ครอบลงไป
conn.begin
conn.send('/queue/test', 'hello');
conn.send('/topic/test', 'hello');
conn.commit


ส่วนกรณีที่ต้องการรับ Message
ก็ให้ subscribe เข้ากับ Topic หรือ Queue ที่ต้องการ
conn.subscribe('/queue/test') { |msg| 
puts msg.body
}

Related link from Roti

No comments: