再看一下,客户端如何进行远程访问。
对应的客户端的配置client.xml,内容如下所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
- <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL" value="tcp://192.168.1.103:61616" />
- </bean>
- <bean id="myQueue" class="org.apache.activemq.command.ActiveMQQueue">
- <constructor-arg value="shirdrnQ" />
- </bean>
- <bean id="myAccountService"
- class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean">
- <property name="serviceInterface" value="org.shirdrn.spring.remote.jms.AccountService" />
- <property name="connectionFactory" ref="connectionFactory" />
- <property name="queue" ref="myQueue" />
- </bean>
- </beans>
主要是基于Spring提供的org.springframework.jms.remoting.JmsInvokerProxyFactoryBean来实现,通过消息中间件代理,调用远程发布的服务。
需要注意的是,客户端是通过消息队列(org.apache.activemq.command.ActiveMQQueue)的名称(如上述为shirdrnQ)来获取消息(远程服务),如果无法识别消息队列是无法实现服务的远程访问的。
客户端实现远程访问,示例代码如下所示:
- package org.shirdrn.spring.remote.jms;
- import org.apache.log4j.Logger;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Client {
- private static final Logger LOG = Logger.getLogger(Client.class);
- static int index = 0;
- private static void invoke(AccountService service) {
- String mobileNo = "1380013800" + (String.valueOf(index++));
- String result = service.shoopingPayment(mobileNo, (byte) 3);
- LOG.info("Client gets result: " + result);
- }
- public static void main(String[] args) throws Exception {
- ApplicationContext ctx = new ClassPathXmlApplicationContext(
- new String[] { "org/shirdrn/spring/remote/jms/client.xml" });
- AccountService service = (AccountService) ctx
- .getBean("myAccountService");
- for(int i=0; i<100; i++) {
- invoke(service);
- }
- }
- }
