Xmpp推送服务smack与springboot的结合使用(三)

来源:互联网 发布:linux php改端口号 编辑:程序博客网 时间:2024/06/15 17:02

介绍

XMPP协议的推送实现采用的smack库,可以与不同的java框架整合使用,这次我使用的springboot框架实现。

这篇文章主要写代码的实现,对XMPP不清楚的,可以看前几篇文章:

java推送技术的选择(一)

openfire服务的安装(二)

搭建springboot项目

这里写图片描述
pom.xml文件,加入jar包

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.example</groupId>    <artifactId>demo</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>demo</name>    <description>Demo project for Spring Boot</description>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.3.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <!--xmpp  smack-->        <dependency>            <groupId>org.igniterealtime.smack</groupId>            <artifactId>smack-core</artifactId>            <version>4.1.8</version>        </dependency>        <dependency>            <groupId>org.igniterealtime.smack</groupId>            <artifactId>smack-tcp</artifactId>            <version>4.1.8</version>        </dependency>        <dependency>            <groupId>org.igniterealtime.smack</groupId>            <artifactId>smack-java7</artifactId>            <version>4.1.8</version>        </dependency>        <dependency>            <groupId>org.igniterealtime.smack</groupId>            <artifactId>smack-extensions</artifactId>            <version>4.1.8</version>        </dependency>        <dependency>            <groupId>org.igniterealtime.smack</groupId>            <artifactId>smack-sasl-provided</artifactId>            <version>4.1.8</version>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build>    <repositories>        <repository>            <id>spring-snapshots</id>            <url>http://repo.spring.io/libs-snapshot</url>        </repository>    </repositories>    <pluginRepositories>        <pluginRepository>            <id>spring-snapshots</id>            <url>http://repo.spring.io/libs-snapshot</url>        </pluginRepository>    </pluginRepositories></project>

与smack结合主要使用的是上面的5个jar包,smack的功能还有很多,需要的可以去看看官方的API文档
>1、smack-core.jar 
XMPP RFC规范定义的XMPP核心功能。

>2、smack-extensions.jar 
XMPP Standards Foundation定义的扩展(XEP)功能。 
包括群聊、文件传输、用户搜索等等。

官方文档地址:
http://download.igniterealtime.org/smack/docs/latest/javadoc/

配置openfire地址

#openfire服务器地址openfire.server=127.0.0.1

发送XMPP消息

连接XMPP服务器

XMPPTCPConnectionConfiguration.Builder config=XMPPTCPConnectionConfiguration.builder();config.setServiceName(openfireServer);config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);config.setSendPresence(true);config.setCompressionEnabled(false);XMPPTCPConnection con = new XMPPTCPConnection(config.build());SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");SASLAuthentication.blacklistSASLMechanism("CRAM-MD5");return con;

实现代码

package com.example.demo;import org.jivesoftware.smack.ConnectionConfiguration;import org.jivesoftware.smack.SASLAuthentication;import org.jivesoftware.smack.packet.Message;import org.jivesoftware.smack.sasl.provided.SASLPlainMechanism;import org.jivesoftware.smack.tcp.XMPPTCPConnection;import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;import org.jivesoftware.smackx.search.ReportedData;import org.jivesoftware.smackx.search.UserSearchManager;import org.jivesoftware.smackx.xdata.Form;import org.springframework.beans.factory.annotation.Value;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * info: * Created by shang on 2017/8/1. */@RestControllerpublic class SmackController {    @Value("${openfire.server}")    protected String openfireServer;    @RequestMapping("")    public Object index(String mobile, String body) {        return sendSmackMessage(mobile, body, false);    }    public boolean sendSmackMessage(String mobile, String body,boolean deliveryReceiptRequest) {        try {            if (StringUtils.isEmpty(mobile)) {                return false;            }            XMPPTCPConnection con = getXmpptcpConnection();            con.connect();            if (con.isConnected()) {                SASLAuthentication.registerSASLMechanism(new SASLPlainMechanism());                con.loginAnonymously();//匿名登录                UserSearchManager userSearchManager=new UserSearchManager(con);                Form searchForm=userSearchManager.getSearchForm("search."+con.getServiceName());                Form answerForm = searchForm.createAnswerForm();                answerForm.setAnswer("Username", true);                answerForm.setAnswer("search", mobile);                ReportedData data=userSearchManager.getSearchResults(answerForm,"search."+con.getServiceName());                List<ReportedData.Row> list = data.getRows();                for (ReportedData.Row row : list) {                    for (String jid : row.getValues("jid")) {                        Message m = new Message();                        m.setBody(body);//设置消息。                        m.setTo(jid);//设置发送目标                        if(deliveryReceiptRequest){                            m.setType(Message.Type.normal);                        }else{                            m.setType(Message.Type.headline);                        }                        m.setSubject(body);                        con.sendStanza(m);                    }                }            }            con.disconnect();            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    private XMPPTCPConnection getXmpptcpConnection() {        XMPPTCPConnectionConfiguration.Builder config=XMPPTCPConnectionConfiguration.builder();        config.setServiceName(openfireServer);        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);        config.setSendPresence(true);        config.setCompressionEnabled(false);        XMPPTCPConnection con = new XMPPTCPConnection(config.build());        SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");        SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");        SASLAuthentication.blacklistSASLMechanism("CRAM-MD5");        return con;    }}

代码解释

  1. getXmpptcpConnection方法为连接XMPP
  2. sendSmackMessage为发送消息的方法,mobile为接收人,body为发送的内容,deliveryReceiptRequest为是否是离线消息
  3. 代码中采用的是匿名发送,也可以指定一个账号作为发送方
  4. 这里我根据需要还用了模糊匹配账号,给匹配的账号都发送了消息
  5. Message.Type.normal与Message.Type.headline是是否离线消息

测试

启动项目后,浏览器输入:http://localhost:8080/?mobile=18758120932&body=测试测试

登录spray客户端,就会接收到消息
这里写图片描述

结束语

以上代码使用就是我在项目中对推送服务的使用,如果在APP内用这样的推送业务,可以选择XMPP服务作为你的选择。

更多的smack的使用可以查看官方文档,聊天,分组,添加好友等功能,完全可以满足你的各种需求。

有问题欢迎给我留言~

阅读全文
0 0