Spring中整合xmpp实例

Spring integration项目中有整合xmpp的功能,参见官方文档http://www.springsource.org/spring-integration

Spring integration主要思想是通道(Channel)和消息(Message)以及Message在Channel中传输的若干机制及控制,对于xmpp同样使用。

但是由于官方文档对xmpp的讲解比较粗,也没有完整的例子,因此本文主要目的是以一个工程例子对此进行扩充。


1、配置

一般情况下在web中只要一个spring配置文件,如果在大型项目中,这将显得较为臃肿,因此可以根据功能插件采取分解的的方法。

在web.xml中加入

<!-- spring 配置 -->  
  <servlet>  
    <servlet-name>mvc-dispatcher</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-*-config.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  

classpath:spring-*-config.xml的意思是spring会在类路径下加载所有匹配的xml配置,可以创建多个这样的xml文件。对xmpp功能来说,可以创建名为spring-xmpp-config.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:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-xmpp="http://www.springframework.org/schema/integration/xmpp"
    xsi:schemaLocation="
	    http://www.springframework.org/schema/integration/xmpp
		http://www.springframework.org/schema/integration/xmpp/spring-integration-xmpp.xsd  
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
       "
       >  
    
    <!-- XMPP Configuration -->   
    <int-xmpp:xmpp-connection
    id="xmppConnection"
    user="stephen-1378454122917"
    password="B8C93759"
    host="www.miitsoft.com"
    port="5222"
    resource="resource"
    subscription-mode="accept_all"/> 
 
    <int:channel id="outboundChannel"/>    
    <int-xmpp:outbound-channel-adapter channel="outboundChannel" xmpp-connection="xmppConnection"/>
 
    
 

    <int-xmpp:inbound-channel-adapter channel="inboundChannel"        
        xmpp-connection="xmppConnection" 
        extract-payload="false"
        auto-startup="true"/>
 
    <int:service-activator input-channel="inboundChannel" method="handleMessage">
        <bean class="com.whyonly.xmpp.MessageReceiver"/>
    </int:service-activator>
 

						
	<bean id="sendMessageService" class="com.whyonly.xmpp.SendMessageService">
        <property name="outboundChannel" ref="outboundChannel"/>
    </bean>					          

</beans>

配置文件的内容较为简单,主要是定义了xmpp连接、inbound和outbound通道,以及xmpp消息接收器和xmpp消息发送服务


2,实现xmpp message的发送和接收


发送:

package com.whyonly.xmpp;


import org.apache.commons.logging.Log;
 
import org.apache.commons.logging.LogFactory;
 
import org.springframework.integration.Message;
 
import org.springframework.integration.MessageChannel;
 
import org.springframework.integration.support.MessageBuilder;
 
import org.springframework.integration.xmpp.XmppHeaders;

 
public class SendMessageService {
 

 
    MessageChannel outboundChannel;
 
    protected final Log logger = LogFactory.getLog(getClass());

    public void setOutboundChannel(MessageChannel outboundChannel) {
        this.outboundChannel = outboundChannel;
    }
 

 
    public Message sendMessageToBuddy(UserInfo user, String message) {
 
        logger.info("Send message("+message+") to " + user.getUserName());
 
        Message<String> xmppOutboundMsg =
                MessageBuilder.withPayload(message)
                .setHeader(XmppHeaders.TO, user.getXMPPUserName()).build();
        outboundChannel.send(xmppOutboundMsg);
        logger.info("Send message finish");
        return xmppOutboundMsg;
 
    }
 
}
 

接收:


package com.whyonly.xmpp;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.core.MessageHandler; 


public class MessageReceiver implements MessageHandler{
	
	 /** Logger for this class and subclasses */
	 
    protected final Log logger = LogFactory.getLog(getClass());

    @ServiceActivator
    @Override
    public void handleMessage(Message msg) throws MessagingException {
    	logger.info("handleMessage()");
        logger.info(msg.getPayload().toString());
        if(msg.getPayload() instanceof org.jivesoftware.smack.packet.Message){
        	String messageStr = ((org.jivesoftware.smack.packet.Message)msg.getPayload()).getBody();
        	logger.info("messageStr="+messageStr);
        }
    }


}

Userinfo.java


package com.whyonly.xmpp;


public class UserInfo  {

   private long userId;

   private String userName;

   

   public UserInfo(long userId, String userName) {

       this.userId = userId;

       this.userName = userName;

   }


   public long getUserId() {

       return userId;

   }



   public void setUserId(long userId) {

       this.userId = userId;

   }



   public String getUserName() {

       return userName;

   }



   public void setUserName(String userName) {

       this.userName = userName;

   }



  public String getXMPPUserName() {

       return userName + "@www.miitsoft.com";

   } 

   

}



3,测试

创建一个cornjob,每一分钟发送一条消息给自己,


package com.whyonly.cornjob.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.whyonly.xmpp.SendMessageService;
import com.whyonly.xmpp.UserInfo;

@Component
public class XmppService {
	
	@Autowired SendMessageService sendMessageService;
 
	@Scheduled(cron="0 0/1 * * * ?")   //every 1 min
	//@Scheduled(cron="0 0 0/1 * * ?")   //every 1 hour
	public synchronized void scanSend(){
		System.out.println("\n\nscan xmpp message neet to be Sent");
		UserInfo user = new UserInfo(1,"stephen-1378454122917");
		String message = "How are you "+ System.currentTimeMillis();
		sendMessageService.sendMessageToBuddy(user, message);
	}

}

为了让spring扫描到此service,可以在spring配置文件中加入

<context:component-scan base-package="com.whyonly.**.service"/>

启动web应用程序后,后台每一分钟打印发送和接收的xmpp消息,如下:


scan xmpp message neet to be Sent
2013-09-06 23:16:00.022  INFO SendMessageService:33 - Send message(How are you 1378480560021) to stephen-1378454122917
2013-09-06 23:16:00.023  INFO SendMessageService:39 - Send message finish
2013-09-06 23:16:00.093  INFO MessageReceiver:21 - handleMessage()
2013-09-06 23:16:00.094  INFO MessageReceiver:22 - org.jivesoftware.smack.packet.Message@624fe5db
2013-09-06 23:16:00.095  INFO MessageReceiver:25 - messageStr=How are you 1378480560021


scan xmpp message neet to be Sent
2013-09-06 23:17:00.023  INFO SendMessageService:33 - Send message(How are you 1378480620023) to stephen-1378454122917
2013-09-06 23:17:00.025  INFO SendMessageService:39 - Send message finish
2013-09-06 23:17:00.094  INFO MessageReceiver:21 - handleMessage()
2013-09-06 23:17:00.095  INFO MessageReceiver:22 - org.jivesoftware.smack.packet.Message@63cc6078
2013-09-06 23:17:00.096  INFO MessageReceiver:25 - messageStr=How are you 1378480620023


scan xmpp message neet to be Sent
2013-09-06 23:18:00.022  INFO SendMessageService:33 - Send message(How are you 1378480680022) to stephen-1378454122917
2013-09-06 23:18:00.024  INFO SendMessageService:39 - Send message finish
2013-09-06 23:18:00.069  INFO MessageReceiver:21 - handleMessage()
2013-09-06 23:18:00.070  INFO MessageReceiver:22 - org.jivesoftware.smack.packet.Message@6420ed7d
2013-09-06 23:18:00.071  INFO MessageReceiver:25 - messageStr=How are you 1378480680022


scan xmpp message neet to be Sent
2013-09-06 23:19:00.024  INFO SendMessageService:33 - Send message(How are you 1378480740024) to stephen-1378454122917
2013-09-06 23:19:00.025  INFO SendMessageService:39 - Send message finish
2013-09-06 23:19:00.091  INFO MessageReceiver:21 - handleMessage()
2013-09-06 23:19:00.092  INFO MessageReceiver:22 - org.jivesoftware.smack.packet.Message@659d681a
2013-09-06 23:19:00.092  INFO MessageReceiver:25 - messageStr=How are you 1378480740024


scan xmpp message neet to be Sent
2013-09-06 23:20:00.050  INFO SendMessageService:33 - Send message(How are you 1378480800050) to stephen-1378454122917
2013-09-06 23:20:00.052  INFO SendMessageService:39 - Send message finish
2013-09-06 23:20:00.117  INFO MessageReceiver:21 - handleMessage()
2013-09-06 23:20:00.118  INFO MessageReceiver:22 - org.jivesoftware.smack.packet.Message@6719e30e
2013-09-06 23:20:00.119  INFO MessageReceiver:25 - messageStr=How are you 1378480800050







Spring Boot是一个用于开发Java应用程序的开源框架,它简化了Spring应用程序的配置和部署过程。XMPP(Extensible Messaging and Presence Protocol)是一种基于XML的协议,用于实时通信,特别是用于即时聊天和在线状态管理。 如果你想在Spring Boot应用程序使用XMPP协议,你可以使用Smack库。Smack是一个开源的XMPP客户端库,它提供了一组易于使用的API来处理XMPP连接、通信和扩展。你可以在你的Spring Boot项目添加Smack依赖,并使用它来建立和管理XMPP连接,发送和接收消息等。 以下是一个简单的示例代码,演示了如何在Spring Boot使用Smack进行XMPP通信: 首先,添加Smack依赖到你的项目的pom.xml文件: ```xml <dependency> <groupId>org.igniterealtime.smack</groupId> <artifactId>smack</artifactId> <version>4.4.4</version> </dependency> ``` 然后,创建一个XMPPManager类来处理XMPP连接和通信: ```java import org.jivesoftware.smack.*; import org.jivesoftware.smack.chat.Chat; import org.jivesoftware.smack.chat.ChatManager; import org.jivesoftware.smack.chat.ChatMessageListener; import org.jivesoftware.smack.packet.Message; public class XMPPManager { private static final String XMPP_SERVER = "your_xmpp_server"; private static final int XMPP_PORT = 5222; private static final String XMPP_USERNAME = "your_username"; private static final String XMPP_PASSWORD = "your_password"; private AbstractXMPPConnection connection; public void connect() throws Exception { XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() .setXmppDomain(XMPP_SERVER) .setHost(XMPP_SERVER) .setPort(XMPP_PORT) .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) .build(); connection = new XMPPTCPConnection(config); connection.connect(); connection.login(XMPP_USERNAME, XMPP_PASSWORD); ChatManager chatManager = ChatManager.getInstanceFor(connection); chatManager.addChatListener(new ChatManagerListener() { public void chatCreated(Chat chat, boolean createdLocally) { chat.addMessageListener(new ChatMessageListener() { public void processMessage(Chat chat, Message message) { String from = message.getFrom(); String body = message.getBody(); // 处理收到的消息 } }); } }); } public void disconnect() { if (connection != null && connection.isConnected()) { connection.disconnect(); } } public void sendMessage(String to, String messageBody) throws Exception { ChatManager chatManager = ChatManager.getInstanceFor(connection); Chat chat = chatManager.createChat(to); chat.sendMessage(messageBody); } } ``` 在你的应用程序,你可以使用XMPPManager类来建立连接、发送消息等。 这只是一个简单的示例,你可以根据你的实际需求进行扩展。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值