Creating a custom Message Service adapter

You can create a custom Message Service adapter for situations where you need functionality that is not provided by one of the standard adapters. A Message Service adapter class must extend the flex.messaging.services.ServiceAdapter class. An adapter calls methods on an instance of a flex.messaging.MessageService object. Both ServiceAdapter and MessageService are included in the public Flex Data Services Javadoc documentation.

The primary method of any Message Service adapter class is the invoke() method, which is called when a client sends a message to a destination. Within the invoke() method, you can include code to send messages to all subscribing clients or to specific clients by evaluating selector statements included with a message from a client.

To send a message to clients, you call the MessageService.pushMessageToClients() method in your adapter's invoke() method. This method takes a message object as its first parameter. Its second parameter is a Boolean value that indicates whether to evaluate message selector statements. You can call the MessageService.sendPushMessageFromPeer() method in your adapter's invoke() method to broadcast messages to peer server nodes in a clustered environment.

package customclasspackage;

import flex.messaging.services.ServiceAdapter;
import flex.messaging.services.MessageService;
import flex.messaging.messages.Message;
import flex.messaging.Destination;

public class SimpleCustomAdapter extends ServiceAdapter {

    public Object invoke(Message message) {
        MessageService msgService = (MessageService)service;
        msgService.pushMessageToClients(message, true);
        msgService.sendPushMessageFromPeer(message, true);
        return null;
    }
}

Optionally, a Message Service adapter can manage its own subscriptions. To do this, you override the ServiceAdapter.handlesSubscriptions() method and return true. You also must override the ServiceAdapter.manage() method, which is passed CommandMessages for subscribe and unsubscribe operations.

The ServiceAdapter class's getAdapterState() and setAdapterState() methods are for adapters that maintain an in-memory state that must be replicated across a cluster. When an adapter starts up, it gets a copy of that state from another cluster node when there is another node running.

To use an adapter class, you must specify it in an adapter-definition element in the Message Services configuration, as the following example shows:

<adapters>
...
    adapter-definition id="cfgateway" class="foo.bar.SampleMessageAdapter"/>
...
</adapters>

Another optional feature that you can implement in an adapter is MBean component management. This lets you expose properties for getting and setting in the administration console. For more information, see Managing services.


Flex 2.01

Take a survey