Simple Data Push
这个简单的数据推送服务demo演示了如何使用消息服务,将数据从服务端推送到客户端。在服务端,一个JAVA组件发布一个模拟真实的值给订阅了此消息目标的FLEX客户端。这种功能常见到股票应用中。
一、运行DEMO:
2、运行客户端程序:http://localhost:8400/spring-flex-testdrive/simplepush/index.html。
3、单击“Subscribe”按钮,被推送的值显示在文本字段中。你可以单击“unsubscribe”按钮取消对这个destnation的订阅。
二、理解代码:
1、simplepush.mxml
该程序通过Consumer向服务端订阅消息,在接收到消息后,将值显示在文本框中。
<mx:Consumer id="consumer" destination="simple-feed" channelSet="{cs}"
通过consumer的subscribe()和unsubscribe()来订阅消息和取消订阅消息。
private function messageHandler(message:IMessage):void
{
}
2、flex-servlet.xml
通过此配置<flex:message-destination id="simple-feed" />,将消息服务暴露给客户端。
3、simpleFeedStarter
simplepush项目只是一个接收数据的应用。启动/停止/发布Feed是通过一JAVA组件来实现的。simpleFeedStarter 是实现此消息服务的bean。可以在flex-servlet.xml直接定义Spring bean,需要在<bean/>标签里使用<flex:remoting-destination />标签。
<bean id="simpleFeedStarter" class="org.springframework.flex.samples.simplefeed.SimpleFeed">
</bean>
simpleFeedStarter bean的构造器注入了默认的消息模版:
<bean id="defaultMessageTemplate" class="org.springframework.flex.messaging.MessageTemplate" />
4、SimpleFeed.java
在SimpleFeed类通过MessageTemplate类来向订阅者发布消息,成员变量template保存了从构造器中注入的MessageTemplate类引用。
SimpleFeed类运行一线程来生成数据,SimpleFeed类有一个内部类FeedThread,是Thread的子类。
public static class FeedThread extends Thread {
SimpleFeed中启动和停止的方法就是操纵FeedThread 线程。
5、feedstarter.mxml
feedstarter负责simpleFeedStarter的启动和停止。feedstarter通过RemoteObject调用服务端上的远程对象。
三、小结:
simplepush程序只是通过consumer的subscribe()和unsubscribe()来订阅消息和取消订阅消息,以及在服务器推送数据时,处理接受到的消息。重要的是SimpleFeed类,simpleFeedStarter bean通过使用Spring注入的MessageTemplate 对象,通过该对象向BlazeDS的目标simple-feed发送消息,此时订阅了simple-feed目标的所有consumer都将收到此消息。
feedstarter start –>simpleFeedStarter bean->simpleFeedStarter.start->FeedThread.start –>FeedThread.run->MessageTemplate send->simple-feed
SimpleFeed的启动/停止在自定义的线程中执行。