JMS - 基于JMS的RPC

本文介绍如何使用Spring框架的JMS模块实现远程服务调用,通过JmsInvokerServiceExporter和JmsInvokerProxyFactoryBean两个核心组件,详细展示了在服务端和客户端之间的消息传递过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在试试通过JMS,在应用程序之间发送消息。
先看看spring提供的RPC方案(其实还有其他方案,只是没见过谁用)。
需要使用到这两个类:
·org.springframework.jms.remoting.JmsInvokerServiceExporter将bean导出为基于消息的服务
·org.springframework.jms.remoting.JmsInvokerProxyFactoryBean让客户端调用服务

 

比较一下JmsInvokerServiceExporter和RmiServiceExporter:

 

package pac.testcase.jms;
public interface JmsRmiService {
    String doServe(String requestedNum);
}

 

package pac.testcase.jms;
import org.springframework.stereotype.Service;
@Service
public class JmsRmiServiceImpl implements JmsRmiService {
                                                                                                                                                     
    public String doServe(String content) {
        System.out.println(content.concat(" has been requested!!"));
        return "your message::".concat(content).concat(":::length:")+content.length();
    }
}

 

将这个pojo声明为服务,在spring配置文件中配置:

<bean id="serverService" class="org.springframework.jms.remoting.JmsInvokerServiceExporter"
    p:serviceInterface="pac.testcase.jms.JmsRmiService"
    p:service-ref="JmsRmiServiceImpl">
</bean>

 

需将他设置为jms监听器,配置方法和一般的jmsMessageListener的配置相同:

<amq:connectionFactory id="jmsFactory" />
<jms:listener-container
    destination-type="queue"
    connection-factory="jmsFactory"
    concurrency="3"
    container-type="simple">
    <jms:listener  destination="sparta" ref="serverService"  />
</jms:listener-container>

 

container-type有simple和default,根据不同的type也可以使用task-Executor,这里先简单记录一下。

先启动jms broker再启动:

new ClassPathXmlApplicationContext("classpath:applicationContext-*.xml").getBean(JmsRmiService.class);

 

client这边我需要一个调用代理帮我去调用接口,也就是JmsInvokerProxyFactoryBean;
配置如下:

<amq:connectionFactory id="connectionFactory" />
<bean id="clientService" class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean"
    p:serviceInterface="pac.test.jms.SenderRmiService"
    p:connectionFactory-ref="connectionFactory"
    p:queueName="sparta"/>

配置中的serviceInterface是client端中根据要调用的方法创建的一个接口。

 

main方法试着调用看看:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    SenderRmiService service = (SenderRmiService)context.getBean("clientService");
    System.out.println(service.doServe("这才是斯巴达!!"));
}

 

server端输出:

client端输出:

转载于:https://www.cnblogs.com/kavlez/p/4071937.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值