MQTT实现服务端推送功能

公司要求做推送功能和即时通讯,又不让使用第三方,查找网上资料,最终采用mqtt
推送实体类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class PushMessage{
	//推送类型
	private String type;
	//标题
	private String title;
	//内容
	private String content;
	//数量
	private Integer badge=1;
	//铃声
	private String sound = "default";
	
	public PushMessage(){
		
	}

	public PushMessage(String type,String title,String content,Integer badge){
		this.type = type;
		this.title = title;
		this.content = content;
		this.badge = badge;
	}
	
	public String getSound() {
		return sound;
	}

	public void setSound(String sound) {
		this.sound = sound;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Integer getBadge() {
		return badge;
	}

	public void setBadge(Integer badge) {
		this.badge = badge;
	}

	@Override
    public String toString() {
		return JSON.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
    }
}
配置文件
mqtt_host=tcp://127.0.0.1
mqtt_port=1883
mqtt_uname=mosquitto
mqtt_pwd=Kdmqtt2016@
mqtt_timeout=10
mqtt_KeepAliveInterval=30

服务端推送工具类
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPushClient {  
  
	protected static final Log logger = LogFactory.getLog(MqttPushClient.class);
	
    private MqttClient client; 
    
    private String clientMac = "admin-12345678abc";

	private static MqttPushClient mqttClientUtil = null;
    
    public static MqttPushClient getInstance(){
    	if(mqttClientUtil == null){
    		mqttClientUtil = new MqttPushClient();
    	}
    	return mqttClientUtil;
    }
    
    private MqttPushClient() {  
    	connect();
    }  
    
    private void connect(){
    	try { 
        	ResourceBundle bundle = ResourceBundle.getBundle("mqtt"); 
        	String host = bundle.getString("mqtt_host") + ":" + bundle.getString("mqtt_port");
        	String userName = bundle.getString("mqtt_uname");
        	String passWord = bundle.getString("mqtt_pwd");
        	Integer timeout = Integer.valueOf(bundle.getString("mqtt_timeout"));
        	Integer keepAliveInterval = Integer.valueOf(bundle.getString("mqtt_KeepAliveInterval"));
            client = new MqttClient(host, clientMac, new MemoryPersistence());  
            MqttConnectOptions options = new MqttConnectOptions();  
            options.setCleanSession(false);  
            options.setUserName(userName);  
            options.setPassword(passWord.toCharArray());  
            options.setConnectionTimeout(timeout);    
            options.setKeepAliveInterval(keepAliveInterval);  
            try {  
                client.setCallback(new PushCallback());  
                client.connect(options); 
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } catch (Exception e) { 
            e.printStackTrace(); 
        }
    }
    
    /**
     * 发布,默认qos为0,非持久化
     * @param topic
     * @param pushMessage
     */
    public void publish(String topic,PushMessage pushMessage){
    	publish(0, false, topic, pushMessage);
    }
    
    /**
     * 发布
     * @param qos
     * @param retained
     * @param topic
     * @param pushMessage
     */
    public void publish(int qos,boolean retained,String topic,PushMessage pushMessage){
    	//connect();
    	MqttMessage message = new MqttMessage();
	    message.setQos(qos);  
	    message.setRetained(retained);  
	    message.setPayload(pushMessage.toString().getBytes());  
	    MqttTopic mtopic = client.getTopic(topic);
	    if(mtopic == null){
	    	logger.error("主题不存在");
	    }
    	MqttDeliveryToken token;
		try {
			token = mtopic.publish(message);
			token.waitForCompletion();  
		} catch (MqttPersistenceException e) {
			e.printStackTrace();
		} catch (MqttException e) {
			e.printStackTrace();
		}  	
    }
    
    /**
     * 订阅某个主题,qos默认为0
     * @param topic
     */
    public void subscribe(String topic){
    	subscribe(topic,0);
    }
    
    /**
     * 订阅某个主题
     * @param topic
     * @param qos
     */
    public void subscribe(String topic,int qos){
    	try {
			client.subscribe(topic, qos);
		} catch (MqttException e) {
			e.printStackTrace();
		}
    }
    
    public String getClientMac() {
		return clientMac;
	}

	public void setClientMac(String clientMac) {
		this.clientMac = clientMac;
	}
	
	public static void main(String[] args) throws Exception {
    	String kdTopic = "test/topic";
    	PushMessage pushMessage = new PushMessage("test", "111", "2222", 1);
    	MqttPushClient.getInstance().publish(0, false, kdTopic, pushMessage);
    	MqttPushClient.getInstance().subscribe(kdTopic);
    	
		/*String[] devs= new String[2];  
        devs[0] = "6a0f20ea25b4fa8beb5086ea159c3c7311f748d56250a6db8a737514a5fea533";
        devs[1] = "d17fcd83b171bd91ac946d14d58b7780a9ac47555e34b7ce2cac77b623b51a5a";
        List<Device> devices=Devices.asDevices(devs);  
        System.out.println(devices.size());  
        IosPushUtil.pushCombinedNotification(pushMessage.toString(), 2, "default", devices);*/
    } 
}  








  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值